evgeny-gavrilov/yii2-many-to-many

Extension many to many relation for Yii2 Framework.

Installs: 1 535

Dependents: 0

Suggesters: 0

Security: 0

Stars: 2

Watchers: 4

Forks: 1

Open Issues: 0

Type:yii2-extension

v1.1.0 2015-11-25 12:59 UTC

This package is auto-updated.

Last update: 2024-04-10 18:55:47 UTC


README

Build Status Packagist Code Climate Test Coverage

This behavior allows to update or delete relations in the junction table, which are described in the model with via() or viaTable().

Behavior doesn't use transaction. Use this method to do transactions() in the model or other way.

Install

php composer.phar require evgeny-gavrilov/yii2-many-to-many

Usage

Connection of behavior and description of the relation in the model

class User extends ActiveRecord
{
    public function behaviors()
    {
        return [
            EvgenyGavrilov\behavior\ManyToManyBehavior::className()
        ];
    }
    
    public function getGroups()
    {
        return $this->hasMany(Group::className(), ['id' => 'group_id'])->viaTable('user_group', ['user_id' => 'id']);
    }
}

Usage in the code

$user = User::findOne(1);
// Add new or update relation
$model->setRelated('groups', [1]);
// or
$model->setRelated('groups', [1, 2]);
$model->save();

// Add or update the data with the remove old relations
$model->setRelated('groups', [1, 2], true);
$model->save();

// Delete all relations
$model->setRelated('groups', [], true);
$model->save();