yii2 get activerecords by relation column
我需要选择具有特定列值的相关 AR 的 ActiveRecord。
情况:"用户"可能有很多"分支"——通过联结表,而分支与部门相关。我有
部门:
1 | ... $this->hasMany(Branch::className(), ['department_id' => 'id']); |
分支:
1 2 | ... $this->hasMany(User::className(), ['id' => 'user_id']) ->viaTable('{{%user_to_branch}}',['branch_id' => 'id']); |
问题是,我不想以任何方式从 Department 访问它(例如
中定义它
所以我可以选择用户喜欢:
1 | User::find()->fromDepartment(5)->all(); |
提前谢谢你!
在 ActiveRecord 中:
1 2 3 4 5 6 7 8 | /** * @inheritdoc * @return MyActiveRecordModelQuery the active query used by this AR class. */ public static function find() { return new MyActiveRecordModelQuery(get_called_class()); } |
MyActiveRecordModelQuery:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | /** * @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; } } |
用法:
1 | MyActiveRecordModelQuery::find()->fromDepartment(5)->all(); |
用户模型方法
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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(); } |
用法:
1 | User::fromDepartment(5); |