使用 with() 从 laravel 中的数据库中仅选择必填字段
Selecting only required fields from DB in laravel using with()
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, ...)
如果我想 select 只使用 laravel 5.6 查询以下必填字段,我该怎么做?
select book_name, book_description from books
select author_name from authors where id in (1, 2, 3, 4, 5, ...)
foreach(Book::with('author' => function($query){ $query->select('id', 'author_name'); })->select('book_name', 'book_description')->get() as $book)
{
echo $book->author->name;
}
使用这个:
Book::with('author:id,author_name')->get(['book_name', 'book_description', 'author_id']);
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, ...)
如果我想 select 只使用 laravel 5.6 查询以下必填字段,我该怎么做?
select book_name, book_description from books
select author_name from authors where id in (1, 2, 3, 4, 5, ...)
foreach(Book::with('author' => function($query){ $query->select('id', 'author_name'); })->select('book_name', 'book_description')->get() as $book)
{
echo $book->author->name;
}
使用这个:
Book::with('author:id,author_name')->get(['book_name', 'book_description', 'author_id']);