Home > Net >  Laravel: sync many to many on a subset of rows
Laravel: sync many to many on a subset of rows

Time:01-30

There is a multi-tenant laravel application that is implemented in a single database. There are models User and Role with the following relation in User model:

public function roles(): BelongsToMany
{
    $relation = $this->belongsToMany(Roles::class, 'role_users', 'user_id', 'role_id')->withTimestamps()->withPivot('tenant_id');
    $relation = $relation->where(function ($query) {
            $query->where('tenant_id', Tenant::current()->id);
        });
    return $relation;
}

The role_users table contains user_id, role_id, tenant_id. A user may present in multiple tenants, when I update roles of a user in a tenant, I need to only update the roles of the current tenant, not the user roles on all tenants. This the code I write :

    $user->roles()->syncWithPivotValues($roles, ['tenant_id' => Tenant::current()->id]);

But it doesn't work and syncs all roles not the roles of the current tenant. How can I solve the problem?

CodePudding user response:

You can use the wherePivot() method passing the tenant id. You can find the documentation here: https://laravel.com/docs/9.x/eloquent-relationships#filtering-queries-via-intermediate-table-columns

The code should then look like this:

$user->roles()->wherePivot('tenant_id', Tenant::current()->id)->sync($roles);
  • Related