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, ...)
解决方法:
用这个:
Book::with('author:id,author_name')->get(['book_name', 'book_description', 'author_id']);