我正在尝试创建一个搜索类来为gridview小部件提供动力。问题是我需要比较主表和联接表中的值。
我正在搜索类中这样做:
$query = User::find();
$query->joinWith(['rank']);
然后在我的过滤器中,我想要类似:
$query->andFilterWhere(['>=', 'user.rank_points', 'rank.promotion_points']);
但是,这不起作用,因为第三个参数rank.promotion_points
gets会以字符串形式转义,并且不会被视为mysql字段。
我试过使用该关系来输出类似的值:
$query->andFilterWhere(['>=', 'user.rank_points', $this->rank->promotion_points]);
但这会给出一个$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')
但是我需要的是:
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')]);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句