我正在尝试创建一个搜索类来支持 gridview 小部件。问题是我需要比较主表和连接表中的值。
我在搜索类中这样做:
$query = User::find();
$query->joinWith(['rank']);
Run Code Online (Sandbox Code Playgroud)
然后在我的过滤器中,我想要类似的东西:
$query->andFilterWhere(['>=', 'user.rank_points', 'rank.promotion_points']);
Run Code Online (Sandbox Code Playgroud)
但这不起作用,因为第三个参数rank.promotion_points被转义为字符串,并且不被视为 mysql 字段。
我曾尝试使用关系输出如下值:
$query->andFilterWhere(['>=', 'user.rank_points', $this->rank->promotion_points]);
Run Code Online (Sandbox Code Playgroud)
但这给出了一个$this没有rank属性的错误。
完成此操作的正确方法是什么?
根据要求编辑,这是上述代码生成的原始查询:
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')
Run Code Online (Sandbox Code Playgroud)
但我需要的是这个:
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`)
Run Code Online (Sandbox Code Playgroud)
整个方法如下所示:
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;
Run Code Online (Sandbox Code Playgroud)
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 | |
+------------------+--------------+------+-----+---------+----------------+
Run Code Online (Sandbox Code Playgroud)
您可以将此条件作为字符串传递:
$query->andWhere('user.rank_points >= rank.promotion_points');
Run Code Online (Sandbox Code Playgroud)
或使用Expression:
$query->andWhere(['>=', 'user.rank_points', new \yii\db\Expression('rank.promotion_points')]);
Run Code Online (Sandbox Code Playgroud)