active-record
active-record copied to clipboard
Laravel's sync() analog in Yii
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?
$user->link('role', $roles);
how does this work? current implemenetation does not support setting multiple models.
@cebe, you are right, there is a loop. I updated the issue.
I started something here, https://github.com/yiisoft/yii2/pull/7103 Hoping for some more discussion.
https://github.com/yii2tech/ar-linkmany
Probably we can implement it in yii3