I have two tables, User
and Post
. One User
can have many posts
and one post
belongs to only one user
If you want to get specific columns using with()
in laravel eloquent then you can use code as below which is originally answered by @Adam in his answer here in response of this same question :
Post::with('user:id,username')->get();
So i have used it in my code but it was giving me error of 1052: Column 'id' in field list is ambiguous
, so if you guys are also facing same problem
Then for solving it you have to specify table name before the id column in with()
method as below code:
Post::with('user:user.id,username')->get();
EmployeeGatePassStatus::with('user:id,name')->get();
In your Post
model
public function user()
{
return $this->belongsTo('User')->select(array('id', 'username'));
}
Original credit goes to Laravel Eager Loading - Load only specific columns
In your Post
model:
public function userWithName()
{
return $this->belongsTo('User')->select(array('id', 'first_name', 'last_name'));
}
Now you can use $post->userWithName
Try with conditions.
$id = 1;
Post::with(array('user'=>function($query) use ($id){
$query->where('id','=',$id);
$query->select('id','username');
}))->get();
When going the other way (hasMany):
User::with(array('post'=>function($query){
$query->select('id','user_id');
}))->get();
Don't forget to include the foreign key (assuming it is user_id in this example) to resolve the relationship, otherwise you'll get zero results for your relation.