编程语言
首页 > 编程语言> > php – 使用with()在laravel中仅选择DB中的必填字段

php – 使用with()在laravel中仅选择DB中的必填字段

作者:互联网

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']);

标签:laravel-5-6,php,laravel
来源: https://codeday.me/bug/20190828/1747405.html