Beginner
Beginner

Reputation: 1740

accessing relationship from model laravel

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

enter image description here

this my table structure for user

enter image description here

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

Answers (3)

Jason Grim
Jason Grim

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

Arnab Rahman
Arnab Rahman

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

J. Doe
J. Doe

Reputation: 1732

Try this:

User::with(['role' => function ($query) {
   $query->where('role_name', 'employee');
}])->get();

Upvotes: 0

Related Questions