使用Laravel的Eloquent关系的错误

I have 2 models - User and RoleUser. Each user is assigned to a role. So I defined a one-to-one relationship by declaring a 'role' method on the User model.

 public function role(){
        return $this->hasOne('Vanguard\RoleUser', 'user_id');
 }

This is my Role Model

class RoleUser extends Model
{
    //
    public $table = 'role_user';

    protected $fillable = ['user_id', 'role_id'];

}

In controller, I am trying to fetch users with role_id = 2 but the query keeps returning all users (i.e. 3) instead of just one user. This is my controller

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

Please what is causing this?

Using a scope with with will only add the scope to the eager loaded relation, regardless of if it exists. To achieve what you want you need to do a whereHas too.

$users = User::whereHas('role', function ($q) {
    $q->where('role_id', 2);
})->with(['role' => function ($q) {
    $q->where('role_id', 2);
}])->get();

Change the query to be something like this:

User::all()->with('role')->where('role_id', 2)->get()

I hope this help.

Assuming you have defined that:

  • A user has one role.
  • A role has many users.

then you can simply write query as:

$role = Role::with('users')->find(2);
$users = $role->users;

The above example will give you all users with role id 2.

Assuming each user may only have one role, then give this a try:

In your User model:

class User extends Model 
{
    public function role()
    {
        return $this->belongsTo(RoleUser::class);
    }
}

In your RoleUser model:

class RoleUser extends Model
{
    public function users()
    {
        return $this->hasMany(User::class);
    }
}

Now, get the data you need (try this in Tinker first):

// Users with role_id 2
$users = User::where('role_id', 2)->get();

// Eager load the Role model to get the entire Role record for each user
$users = User::with('role')->where('role_id', 2)->get();

// Get role's where role_id is 2, and eager load the users
$role = RoleUser::with('users')->where('id', 2)->get();