3

我需要选择具有相关 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 访问它(例如 $department->getUsers()....),但我想在ActiveQuery.

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

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

先感谢您 !

4

2 回答 2

0

在 ActiveRecord 中:

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

我的活动记录模型查询:

/**
 * @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();
于 2015-10-08T14:30:37.280 回答
-1

用户模型方法

public function getBranch()
{
    return $this->hasMany(Branch::className(), ['id' => 'branch_id'])
                ->viaTable('{{%user_to_branch}}', ['user_id' => 'id']);
}

public static function fromDepartment($id)
{
    $query = self::find();
    $query->joinWith(['branch'])
          ->andWhere(['department_id'=>$id]);
    return $query->all();
}

用法:

User::fromDepartment(5);
于 2015-10-08T14:32:59.983 回答