yiisoft / active-record

Active Record database abstraction layer
https://www.yiiframework.com/
BSD 3-Clause "New" or "Revised" License
65 stars 27 forks source link

ActiveRecord::setRelation() method #50

Open Chofoteddy opened 8 years ago

Chofoteddy commented 8 years ago

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?

Faryshta commented 8 years ago

7040

1990

alex-code commented 8 years ago

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

klimov-paul commented 8 years ago

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

alex-code commented 8 years ago

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

Chofoteddy commented 6 years ago

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

samdark commented 6 years ago

Definitely not the next release.

cebe commented 6 years ago

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

Tigrov commented 3 weeks ago

Related with #59