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

ActiveRecord::setRelation() method

Open Chofoteddy opened this issue 9 years ago • 8 comments

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]);

captura de pantalla de 2015-07-21 22 17 18

can we implement something like this on the core?

Chofoteddy avatar Jul 22 '15 02:07 Chofoteddy

#7040 #1990

Faryshta avatar Jul 22 '15 02:07 Faryshta

https://github.com/yiisoft/yii2/pull/7103 Something I started here.

alex-code avatar Jul 22 '15 07:07 alex-code

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

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

@klimov-paul That's a handy behavior, be nice if something like this was part of yii2.

alex-code avatar Sep 22 '15 09:09 alex-code

Any update on this issue? Can we get it on next release?

Chofoteddy avatar Aug 01 '17 02:08 Chofoteddy

Definitely not the next release.

samdark avatar Aug 01 '17 07:08 samdark

This is something for https://github.com/yiisoft/yii2-collection specifically https://github.com/yiisoft/yii2-collection/issues/6

cebe avatar Aug 02 '17 23:08 cebe

Related with #59

Tigrov avatar Jun 08 '24 11:06 Tigrov