Reputation: 1740
i have a two tables where user table has a one to one relationship with role table
this is my user model
public function role(){
return $this->belongsTo(Role::class);
}
this is my role model
public function user(){
return $this->hasOne(User::class);
}
this my table structure for role
this my table structure for user
how can i access in my user model the role which is equal to employee i tried
User::with('role')->where('role_name','employee')->get();
but it has an error
role_name column not found
Upvotes: 0
Views: 63
Reputation: 413
Try this:
User::whereHas('role', function ($query) {
$query->where('role_name', 'employee');
})->get();
Details at: https://laravel.com/docs/5.4/eloquent-relationships#querying-relationship-existence
Upvotes: 1
Reputation: 1013
This will give you only the users which has an employee role .
User::whereHas('role', function ($query) {
$query->where('role_name', 'employee');
})->get();
And this will give you all the users with their employee roles if any exist
User::with(['role' => function ($query) {
$query->where('role_name', 'employee');
}])->get();
Upvotes: 3
Reputation: 1732
Try this:
User::with(['role' => function ($query) {
$query->where('role_name', 'employee');
}])->get();
Upvotes: 0