active-record icon indicating copy to clipboard operation
active-record copied to clipboard

Laravel's sync() analog in Yii

Open akireikin opened this issue 10 years ago • 5 comments

I have 2 AR models: User and Role connected via junction table. I need to ensure that only certain Role models attached to User model. IDs of roles are given.

In Laravel I can write:

$ids = [1, 2, 3];
$user->roles()->sync($ids);

Now, in Yii I do the same thing this way:

$ids = [1, 2, 3];
$user->unlinkAll('role', true);
$roles = Role::find()->where(['id' => $ids)->all();
foreach ($roles as $role) {
    $user->link('role', $role);
}

Is it possible to sync links between models without unnecessary creation of Role entities and deleting all previous connections?

akireikin avatar Apr 13 '15 17:04 akireikin

$user->link('role', $roles);

how does this work? current implemenetation does not support setting multiple models.

cebe avatar Apr 13 '15 18:04 cebe

@cebe, you are right, there is a loop. I updated the issue.

akireikin avatar Apr 13 '15 19:04 akireikin

I started something here, https://github.com/yiisoft/yii2/pull/7103 Hoping for some more discussion.

alex-code avatar Apr 14 '15 08:04 alex-code

https://github.com/yii2tech/ar-linkmany

klimov-paul avatar Aug 26 '15 13:08 klimov-paul

Probably we can implement it in yii3

rustamwin avatar Nov 23 '18 11:11 rustamwin