I am trying to eager load a model in laravel but only return certain columns. I do not want the whole eager loaded table being presented.
public function car() { return $this->hasOne('Car', 'id')->get(['emailid','name']); }
I am getting the following error:
log.ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Call to undefined method Illuminate\Database\Eloquent\Collection::getAndResetWheres()'
Select specific columns with Laravel Eloquent To get all of the columns from the users table, we would use the following: $user = User::where('username', 'bobbyiliev')->get(); However, if you wanted to get only a specific column, you could pass it as an argument to the get() method.
While lazy loading delays the initialization of a resource, eager loading initializes or loads a resource as soon as the code is executed. Eager loading also involves pre-loading related entities referenced by a resource.
Eager loading is super simple using Laravel and basically prevents you from encountering the N+1 problem with your data. This problem is caused by making N+1 queries to the database, where N is the number of items being fetched from the database.
Eager loading is the process whereby a query for one type of entity also loads related entities as part of the query. Eager loading is achieved by the use of the Include method. It means that requesting related data be returned along with query results from the database.
Make use of the select()
method:
public function car() { return $this->hasOne('Car', 'id')->select(['owner_id', 'emailid', 'name']); }
Note: Remember to add the columns assigned to the foreign key matching both tables. For instance, in my example, I assumed a Owner
has a Car
, meaning that the columns assigned to the foreign key would be something like owners.id = cars.owner_id
, so I had to add owner_id
to the list of selected columns;
Also you don't need to specify getting specific columns in the model and the relationship method itself... You can do that whenever you need it... Like this:
$owners = Owner:: with([ 'car' => function($q) { $q->select('id', 'owner_id', 'emailid', 'name'); }, 'bike' => function($q) { $q->select('id', 'owner_id', 'emailid', 'name'); } ])-> get();
In this way you can also get all of the columns of the related model if you have ever needed to.
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