foreach(Book::with('author')->get() as $book)
{
echo $book->author->name;
}
上面的循环类似于以下两个查询:
select * from books
select * from authors where id in (1, 2, 3, 4, 5, ...)
如果我想使用laravel 5.6只选择下面所需的字段查询,我该怎么办?
select book_name, book_description from books
select author_name from authors where id in (1, 2, 3, 4, 5, ...)
答案 0 :(得分:4)
foreach(Book::with('author' => function($query){ $query->select('id', 'author_name'); })->select('book_name', 'book_description')->get() as $book)
{
echo $book->author->name;
}
答案 1 :(得分:1)
使用此:
Book::with('author:id,author_name')->get(['book_name', 'book_description', 'author_id']);