如何向结点 table 添加行为?

How to add behaviour to a junction table?

我有用户、角色 table 和一个联结点 table role_user 用于这些 table 之间的多对多关系。

时间戳和 Blameable 行为适用于用户和角色 tables 但我也想将这些行为添加到我的连接 table。

我的模特是;

User.php

namespace backend\models;

use yii\behaviors\BlameableBehavior;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveQuery;
use yii\db\ActiveRecord;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "user".
 *
 * @property integer $id
 * @property string $username
 * @property string $auth_key
 * @property string $password_hash
 * @property string $password_reset_token
 * @property string $email
 * @property integer $status
 * @property integer $created_at
 * @property integer $updated_at
 * @property string $name
 * @property string $surname
 * @property integer $role_id
 */
class User extends ActiveRecord {

    const STATUS_DELETED = 0;
    const STATUS_ACTIVE = 10;

    public static function getStates() {
        return ArrayHelper::map([
                    ['id' => User::STATUS_ACTIVE, 'name' => 'Active'],
                    ['id' => User::STATUS_DELETED, 'name' => 'Deleted'],
                        ], 'id', 'name');
    }

    /**
     * @inheritdoc
     */
    public function behaviors() {
        return [
            TimestampBehavior::className(),
            BlameableBehavior::className()
        ];
    }

    /**
     * @inheritdoc
     */
    public static function tableName() {
        return 'user';
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['username', 'auth_key', 'password_hash', 'email'], 'required'],
            [['status', 'created_at', 'updated_at', 'created_by', 'updated_by'], 'integer'],
            [['username', 'password_hash', 'password_reset_token', 'email', 'name', 'surname'], 'string', 'max' => 255],
            [['auth_key'], 'string', 'max' => 32],
            [['email'], 'unique'],
            [['password_reset_token'], 'unique'],
            [['username'], 'unique']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'username' => 'Username',
            'auth_key' => 'Auth Key',
            'password_hash' => 'Password Hash',
            'password_reset_token' => 'Password Reset Token',
            'email' => 'Email',
            'status' => 'Status',
            'created_at' => 'Created At',
            'updated_at' => 'Updated At',
            'created_by' => 'Created By',
            'updated_by' => 'Updated By',
            'name' => 'Name',
            'surname' => 'Surname',
            'roles' => 'Roles',
        ];
    }

    /**
     * @return ActiveQuery
     */
    public function getRoles() {
        return $this->hasMany(Role::className(), ['id' => 'role_id'])
                        ->viaTable(RoleUser::tableName(), ['user_id' => 'id']);
    }

}

Role.php

namespace backend\models;

use yii\behaviors\BlameableBehavior;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveQuery;
use yii\db\ActiveRecord;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "role".
 *
 * @property integer $id
 * @property string $name
 * @property integer $status
 * @property string $created_at
 * @property string $updated_at
 *
 * @property User[] $users
 */
class Role extends ActiveRecord {

    const STATUS_DELETED = 0;
    const STATUS_ACTIVE = 10;

    public static function getStates() {
        return ArrayHelper::map([
                    ['id' => Role::STATUS_ACTIVE, 'name' => 'Active'],
                    ['id' => Role::STATUS_DELETED, 'name' => 'Deleted'],
                        ], 'id', 'name');
    }

    /**
     * @inheritdoc
     */
    public function behaviors() {
        return [
            TimestampBehavior::className(),
            BlameableBehavior::className()
        ];
    }

    /**
     * @inheritdoc
     */
    public static function tableName() {
        return 'role';
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['status', 'created_at', 'updated_at', 'created_by', 'updated_by'], 'integer'],
            [['name'], 'string', 'max' => 255]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'name' => 'Name',
            'status' => 'Status',
            'created_at' => 'Created At',
            'updated_at' => 'Updated At',
            'created_by' => 'Created By',
            'updated_by' => 'Updated By',
        ];
    }

    /**
     * @return ActiveQuery
     */
    public function getUsers() {
        return $this->hasMany(User::className(), ['role_id' => 'id']);
    }

}

角色User.php

<?php

namespace backend\models;

use yii\behaviors\BlameableBehavior;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveQuery;
use yii\db\ActiveRecord;

/**
 * This is the model class for table "role_user".
 *
 * @property integer $id
 * @property integer $user_id
 * @property integer $role_id
 *
 * @property Role $role
 * @property User $user
 */
class RoleUser extends ActiveRecord {

    /**
     * @inheritdoc
     */
    public function behaviors() {
        return [
            TimestampBehavior::className(),
            BlameableBehavior::className()
        ];
    }

    /**
     * @inheritdoc
     */
    public static function tableName() {
        return 'role_user';
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['user_id', 'role_id'], 'required'],
            [['user_id', 'role_id', 'status', 'created_at', 'updated_at', 'created_by', 'updated_by'], 'integer'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'user_id' => 'User ID',
            'role_id' => 'Role ID',
            'created_at' => 'Created At',
            'updated_at' => 'Updated At',
            'created_by' => 'Created By',
            'updated_by' => 'Updated By',
        ];
    }

    /**
     * @return ActiveQuery
     */
    public function getRole() {
        return $this->hasOne(Role::className(), ['id' => 'role_id']);
    }

    /**
     * @return ActiveQuery
     */
    public function getUser() {
        return $this->hasOne(User::className(), ['id' => 'user_id']);
    }

}

当我link使用 ActiveRecord 的 link 方法为用户分配角色时:

$user->link('roles', Role::findOne($role_id));

是否有更好的方法来 link 这些具有这些行为的模型,或者我应该通过从 RoleUser 模型创建实例来 linking 吗?

提前致谢。

如果你想让 Yii 在 link 方法中使用你的 RoleUser class 那么你应该使用 via 而不是 viaTable 来定义关系。

声明附加关系:

User.php

public function getRoleLinks()
{
    return $this->hasMany(UserRole::className(), ['user_id' => 'id']);
}

并修改你的用户->角色关系:

public function getRoles() {
    return $this->hasMany(Role::className(), ['id' => 'role_id'])
        ->via('roleLinks');
}

如果你使用 viaTable 那么 yii 会直接将新记录插入 user_role 而无需实例化 UserRole class。

p.s。反之亦然,如果你想调用 $role->link('users', $user)