yii2 按关系列获取活动记录
yii2 get activerecords by relation column
我需要 select ActiveRecord,它具有具有特定列值的相关 AR。
情况:'User' 可能有很多 'Branches' - 通过交叉点 table,分支与部门相关。我有 department_id
,我想要 select 个拥有来自这个部门的分支机构的用户。
部门:
... $this->hasMany(Branch::className(), ['department_id' => 'id']);
分支机构:
... $this->hasMany(User::className(), ['id' => 'user_id'])
->viaTable('{{%user_to_branch}}',['branch_id' => 'id']);
问题是,我不想以任何方式从部门访问它(例如 $department->getUsers()
...),但我想在 ActiveQuery
.[= 中定义它16=]
所以我可以 select 用户喜欢:
User::find()->fromDepartment(5)->all();
提前致谢!
在 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();
用户模型方法
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);
我需要 select ActiveRecord,它具有具有特定列值的相关 AR。
情况:'User' 可能有很多 'Branches' - 通过交叉点 table,分支与部门相关。我有 department_id
,我想要 select 个拥有来自这个部门的分支机构的用户。
部门:
... $this->hasMany(Branch::className(), ['department_id' => 'id']);
分支机构:
... $this->hasMany(User::className(), ['id' => 'user_id'])
->viaTable('{{%user_to_branch}}',['branch_id' => 'id']);
问题是,我不想以任何方式从部门访问它(例如 $department->getUsers()
...),但我想在 ActiveQuery
.[= 中定义它16=]
所以我可以 select 用户喜欢:
User::find()->fromDepartment(5)->all();
提前致谢!
在 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();
用户模型方法
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);