John Davidson

php - Specific columns using eloquent in a nested eager loading

0 comments
Message:


Is there a way to only limit the number of columns that one can select in a nested eager loading in Laravel?


Currently, I have 3 models that inter-relate. For instance, let's assume that we have the Publisher model, Authors model, and books model.


A publisher has a relationship with the Authors and the Authors have a relation with the book's models.


The Publisher model has columns like:



  • id

  • name

  • address

  • fax number

  • email address


The author's models contain:



  • id

  • name

  • address

  • email

  • published books

  • publishers_id


The books models contain:



  • id

  • title

  • authors_id

  • published_on

  • category


If I want to check the books that have been published by a given publication company: This is how I pull the records


$published_books::Publisher::with('authors.books')->take(1);

With this, I get a response like this:


"id" : 1,
"name" : "Longhorn Ke",
"address" : "14th Street",
"fax number" : "null",
"email_address" : "[email protected]",
"author" :{
"id" : 4,
"name" : patel,
"email" : [email protected],
"published_books" : 12,
"publishers_id" : 1,
"books" : {
"id": 1,
"title" : "Art of life",
"authors_id" : 1,
"published_on" : "2020-07-12 14:22:25",
"category" : "Life teachings",
}

}



What I want is that when I load a book through the relationship I only want to get the name of the publisher, name of the author and the books details as shown below:


"id" : 1,
"name" : "Longhorn Ke",
"author" :{
"id" : 4,
"name" : patel,
"books" : {
"id": 1,
"title" : "Art of life",
"authors_id" : 1,
"published_on" : "2020-07-12 14:22:25",
"category" : "Life teachings",
}

}

How can I achieve that using eloquent? At this point, I understand that eloquent allows selection of specific columns on a nester load as shown in this link https://laravel.com/docs/master/eloquent-relationships#eager-loading-specific-columns but how do I do it in all the models to achieve the code result show above



My Answer:
>select('id', 'name', 'address')
->where('id', $publisher_id)
->get();

This will retrieve all the columns from the Publisher model. If you want to limit the columns that are retrieved from the Authors and Books models, you can specify the columns in the `with` method like this:

php
$published_books = Publisher::with(['authors' => function ($query) {
$query->select('id', 'name', 'address');
}, 'authors.books' => function ($query) {
$query->select('id', 'title', 'published_on', 'category');
}])
->where('id', $

Rate this post

4 of 5 based on 5311 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us