سؤال

I got category_to_news and news_main table

category_to_news

  • news_id int
  • name varchar
  • title timestamp

news_main

  • id int
  • title varchar
  • image varchar
  • created_at timestamp

how to return by news_main's field and category_news's field ? I've tried this method and it's not work

$posts = Categorytonews::with(array(
    'Newsmain' => function($query)
    {
        $query->orderBy('id', 'DESC')->select(array('title', 'id', 'created_at', 'image'));
    }
    ))
    ->get( );
هل كانت مفيدة؟

المحلول 2

$posts = Categorytonews::with(array('Newsmain' => function($query)
{
    $query->select(array('title', 'id', 'created_at', 'image'))->orderBy('id', 'DESC');
}))->get();

نصائح أخرى

You need join for this because with() runs another query, so ordering there won't do the job:

$posts = Categorytonews::with('Newsmain') // get all fields from Newsmain
  ->join('news_main', 'category_to_news.news_id', '=', 'news_main.id') // join for ordering
  ->orderBy('news_main.id','desc') // order by joined field
  ->get('category_to_news.*'); // select only main table, you don't need joined fields
                               // on Categorytonews model - they will be loaded by with()
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top