如何在Laravel中通过急切加载选择另一个表连接中的字段

时间:2014-04-25 02:40:34

标签: laravel-4 eloquent

我有category_to_news和news_main table

category_to_news

  • news_id int
  • name varchar
  • title timestamp

news_main

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

如何通过news_main的字段和category_news的字段返回?我已经尝试过这种方法而且它不起作用

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

2 个答案:

答案 0 :(得分:1)

你需要加入这个,因为with()运行另一个查询,所以在那里订购不会做这个工作:

$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()

答案 1 :(得分:0)

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