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

deekepMaks's avatar

belongsToMany and mongodb

I have 3 tables: users, roles and user_role (link table)

I need to get all the user’s roles in a readable form, that is, using the connection table, pull out everything I need from the roles table for a specific user For this I use:

public function roles()
    {
        return $this->belongsToMany(RolesModel::class, 'user_role', 'user_id', 'role_id');
    }

At the output I get an empty array, although there is definitely data in the database

I checked for data availability this way:

 $user_role = UserRoleModel::where('user_id', $this->id)->first();
$role = RolesModel::where('_id', $user_role->role_id)->first();

And the result was the role I needed What am I doing wrong in the belongsToMany() query?

0 likes
0 replies

Please or to participate in this conversation.