foreach(Book::with('author')->get() as $book)
{
echo $book->author->name;
}
Above loop is like below two queries:
select * from books
select * from authors where id in (1, 2, 3, 4, 5, ...)
If i want to select only required fields like below query using laravel 5.6, how can I do it?
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With