I want to do the following.
I have three models: User
, Business
, Role
They are connected as follows: Users can have many roles, and belong to multiple businesses.
Roles are predefined.
I want that each user can have different roles in different businesses. For example, in business1 the users has role sales manager
, but in business2 he has role director
. User can have multiple roles on same business.
User
model:
public function businesses()
{
return $this->belongsToMany('App\Business')->withTimestamps();
}
Business
model:
public function users()
{
return $this->belongsToMany('App\Business')->withTimestamps();
}
Pivot table:
Schema::create('business_user', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->integer('business_id')->unsigned();
$table->integer('user_id')->unsigned();
$table->integer('role_id')->unsigned();
});
I add the User
to the Business
as:
$user->businesses()->attach($business_id, ['role_id' => $roleId]);
This should add the row in pivot table as: ['1','2','3'].
My questions are:
- Is this the right way to do this?
- How do I proceed with detach method?
$user->businesses()->detach($business_id)->where('role_id',$role_id);
This is not the correct syntax but something like this. If the user has two roles in a business (for example: 'director' and 'sales manager') on detach I want to remove just one of the roles (for example: 'director') and not all of them. I believe that running$user->businesses()->detach($business_id);
will detach all roles. - Is there a way to use the
sync()
method with this?
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire