Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting only required fields from DB in laravel using with()

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, ...)
like image 282
Mȍhǟmmǟd Șamȋm Avatar asked Apr 07 '26 03:04

Mȍhǟmmǟd Șamȋm


1 Answers

foreach(Book::with('author' => function($query){ $query->select('id', 'author_name'); })->select('book_name', 'book_description')->get() as $book)
{ 
   echo $book->author->name;
}
like image 131
Luis felipe De jesus Munoz Avatar answered Apr 08 '26 18:04

Luis felipe De jesus Munoz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!