active-record
active-record copied to clipboard
ActiveRecord::setRelation() method
Basically it will take the relation name, the ids to set and will insert/delete from the database accordingly.
Here is the code I am using on my ActiveRecord
/**
* @param array $ids
* @param string $name The relation name
* @param boolean $delete Whether to delete the model that contains the foreign key.
*/
public function setRelation($name, $ids, $delete = false)
{
$relationQuery = $this->getRelation($name);
$modelClass = $relationQuery->modelClass;
$primaryKey = $modelClass::primaryKey();
$relationQuery->select($primaryKey);
foreach ($modelClass::find()
->andWhere(['in', $primaryKey, $ids])
->andWhere(['not in', $primaryKey, $relationQuery])
->each() as $model
) {
$this->link($name, $model);
}
foreach ($relationQuery->andWhere(['not in', $primaryKey, $ids])
->each() as $model
) {
$this->unlink($name, $model, $delete);
}
}
Example 1:
/* @var $model common\models\Restaurant */
$model = $this->findModel($id);
/*
* It will link the models with id 1,5,6 (if not there already)
* and delete those that already exist and the id can not pass on the list.
*/
$model->setRelation('usersAssist', [1,5,6]);
Example 2:
/* @var $model common\models\Form */
$model = $this->findModel($id);
$model->setRelation('usersBcc', [2,3]);
$model->setRelation('usersCc', [5]);
can we implement something like this on the core?
#7040 #1990
https://github.com/yiisoft/yii2/pull/7103 Something I started here.
https://github.com/yii2tech/ar-linkmany
@klimov-paul That's a handy behavior, be nice if something like this was part of yii2.
Any update on this issue? Can we get it on next release?
Definitely not the next release.
This is something for https://github.com/yiisoft/yii2-collection specifically https://github.com/yiisoft/yii2-collection/issues/6
Related with #59