Search code examples
controlleryii2many-to-manypivot-table

Link pivot table in Yii2


I have one many to many relationship model. There are two tables user and entity. and I have created one another table user_entity to apply many-to-many relationship.

user.php

public function getEntities()
{
    return $this->hasMany(Entity::class, ['id' => 'entity_id'])
        ->viaTable('drs_user_entity', ['user_id' => 'id']);
}

entity.php

public function getUsers() {
    return $this->hasMany(User::class, ['id' => 'user_id'])
      ->viaTable('drs_user_entity', ['entity' => 'id']);
}

Now if user changes it entities, how can I make changes in user_entity table?

Note: I have already tried regular first delete and then add new data to user_entity. and it's an API controller, I send entity details in this format:

enter image description here


Solution

  • Would you try this? Connect to pivot with hasMany then users from there. It will probably solve your problem this way.

    $entityModels[0]->pivot->users;