我正在尝试创建一个搜索类来支持 gridview 小部件。问题是我需要比较主表和连接表中的值。
我在搜索类中这样做:
$query = User::find();
$query->joinWith(['rank']);
然后在我的过滤器中,我想要类似的东西:$query->andFilterWhere(['>=', 'user.rank_points', 'rank.promotion_points']);
但这不起作用,因为第三个参数 rank.promotion_points
被转义为字符串,不被视为 mysql 字段。我曾尝试使用关系输出如下值:
$query->andFilterWhere(['>=', 'user.rank_points', $this->rank->promotion_points]);
但这给出了一个错误 $this
没有 rank
属性(property)。完成此操作的正确方法是什么?
根据要求编辑,这是上述代码生成的原始查询:
SELECT `user`.*
FROM `user`
LEFT JOIN `rank`
ON `user`.`rank_id` = `rank`.`id`
WHERE (`rank_id` NOT IN (1, 2, 3, 4, 5, 6))
AND (`user`.`rank_points` >= 'rank.promotion_points')
但我需要的是这个:SELECT `user`.*
FROM `user`
LEFT JOIN `rank`
ON `user`.`rank_id` = `rank`.`id`
WHERE (`rank_id` NOT IN (1, 2, 3, 4, 5, 6))
AND (`user`.`rank_points` >= `rank`.`promotion_points`)
整个方法如下所示:public function search($params)
{
$query = User::find();
$query->joinWith(['rank']);
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'id' => $this->id,
'rank_id' => $this->rank_id,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
]);
$query->andFilterWhere(['like', 'username', $this->username]);
$query->andFilterWhere(['not in', 'rank_id', [1, 2, 3, 4, 5, 6]]);
$query->andFilterWhere(['>=', 'user.rank_points', 'rank.promotion_points']);
return $dataProvider;
rank
表架构:+------------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | NO | UNI | NULL | |
| rank_points | int(11) | YES | | NULL | |
| promotion_points | int(11) | YES | | NULL | |
+------------------+--------------+------+-----+---------+----------------+
最佳答案
您可以将此条件作为字符串传递:
$query->andWhere('user.rank_points >= rank.promotion_points');
或使用 Expression
:$query->andWhere(['>=', 'user.rank_points', new \yii\db\Expression('rank.promotion_points')]);
关于php - 如何比较 Yii2 ActiveDataProvider 中连接表的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63662964/