I have two models, User and Role. These two models have many-to-many relationship between each other with pivot table role_user. In this pivot table are values user_id, role_id and meta_value. meta_value is important, because it is foreign key (in database just int) of other models. The other model is chosen by Roles mate_type.
User migration:
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
Role migration:
Schema::create('roles', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->string('name');
$table->integer('meta_type')->nullable();
});
Role_user migration:
Schema::create('role_user', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->foreignId('role_id')->constrained()->onDelete('cascade');
$table->integer('meta_value')->nullable();
});
These meta values are used if the role is dependent on other models. In practise, if I have a Role named "Team member", the Role will have a meta type of Team (I am using numbers to determine that).
And now, I need to select somehow all users that have the role of team member with the specific team (in meta).
I tried:
$user = User::with('roles')->where(column: 'meta_type', "=", "2")->wherePivot("meta_value", "=", $team_id)->get();
$users = User::all()->with('roles')->where("pivot_meta_value", "=", $team_id)->get();
$users = User::whereHas('roles', function($q) {
$q->whereIn('meta_value', 2);
})->get();
And many more, but all without success.
Does anyone know how to do it?