yiisoft / yiisoft/active-record
ActiveRecord::setRelation() method
Open
@cebe is already working on this.
Since Aug 2, 2017.
- Dominant language
- PHP
- Stars
- 119
- Forks
- 38
- Avg merge
- 1h 11m
- Merged PRs (30d)
- 1
Description
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?
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Assessment
This issue has not been assessed yet.