Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

tnort's avatar
Level 4

Users that have role of supervisor and teaches IT

I have 3 tables users, roles and fields.

The relations between users and fields are stored in pivot table field_user while the users and their roles are stored is role_user.

User class

public function roles() { return $this->belongsToMany(Role::class); }

public function fields()
{
    return $this->belongsToOne(Field::class);
}

Field class

public function users() { return $this->belongsToMany(User::class); }

Role class public function users() { return $this->belongsToMany(User::class); }

How to get all users that have role supervisors and belong to the IT field.

I managed to get all supervisors with

$supervisors = User::whereHas('roles', function ($query) use($role_name) {

    $query->where('name', $role_name);

    })->get();

but I cannot figure out how to filer only those with IT field

0 likes
8 replies
jlrdw's avatar

If you search medium they have some decent articles on this subject.

Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

How about two where has?

$supervisors = User::whereHas('roles', function ($query) use($role_name) {

    $query->where('name', $role_name);

    })->whereHas('fields', function ($query) use($field_name) {

    $query->where('name', $field_name);

    })->get();
tnort's avatar
Level 4

I got an error

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.fields_id' in 'where clause' (SQL: select * from users where exists (select * from roles inner join role_user on roles.id = role_user.role_id where users.id = role_user.user_id and name = supervisor) and exists (select * from fields where users.fields_id = fields.id and name = IT))

tnort's avatar
Level 4

'users.fields_id' shoudl actually be users.user_id

Sinnbeck's avatar

Just curious. If there is a direct relation to a specific field?

I assume the belongsToOne is from a package? Perhaps they don't support whereHas

tnort's avatar
Level 4

seems like belongsToMany would work perfectly fine but not belongsTo or belongsToOne

tnort's avatar
Level 4

I would love to speak with you in private, how can we sort it out?

Sinnbeck's avatar

For BelongsTo to work the user model needs a field_id on the table

Please or to participate in this conversation.