yii2通过关系列获取activerecords

时间:2015-10-08 14:16:33

标签: activerecord yii2 yii2-advanced-app yii2-model

我需要选择具有特定列值的相关AR的ActiveRecord

情况:'用户'可能有很多分行' - 通过联结表,与分部相关。我有department_id,我想选择有来自这个部门的分支的用户。

系:

... $this->hasMany(Branch::className(), ['department_id' => 'id']);

科:

... $this->hasMany(User::className(), ['id' => 'user_id'])
                ->viaTable('{{%user_to_branch}}',['branch_id' => 'id']);

问题是,我不想以任何方式从部门访问此内容(例如$department->getUsers() ....),但我想在ActiveQuery中定义此内容。

所以我可以选择像这样的用户:

User::find()->fromDepartment(5)->all();

提前感谢你!

1 个答案:

答案 0 :(得分:0)

在ActiveRecord中:

/**
 * @inheritdoc
 * @return MyActiveRecordModelQuery the active query used by this AR class.
 */
public static function find()
{
    return new MyActiveRecordModelQuery(get_called_class());
}

MyActiveRecordModelQuery:

/**
 * @method MyActiveRecordModelQuery one($db = null)
 * @method MyActiveRecordModelQuery[] all($db = null)
 */
class MyActiveRecordModelQuery extends ActiveQuery
{
    /**
     * @return $this
     */
    public function fromDepartment($id)
    {
        $this->andWhere(['departament_id' => $id]); //or use relation

        return $this;
    }
}

用法:

MyActiveRecordModelQuery::find()->fromDepartment(5)->all();