evgeny-gavrilov/yii2-many-to-many

为 Yii2 框架扩展多对多关系。

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

This package is auto-updated.

Last update: 2024-09-10 19:47:37 UTC


README

Build Status Packagist Code Climate Test Coverage

此行为允许更新或删除由模型中的 via()viaTable() 描述的连接表中的关系。

行为不使用事务。在模型或其他方式中使用此方法进行 transactions()

安装

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

使用方法

行为与模型中关系的连接及描述

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

代码中的使用

$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();