我一直试图在Yii 2中对计算出的case语句列进行过滤,这就是我在搜索模型中所拥有的:
$query = Pricing::find();
$query->select("*, (CASE WHEN MyPrice > CompetitorPrice THEN 'Higher' WHEN MyPrice = CompetitorPrice THEN 'Equal' ELSE 'Lower' END) AS standing");
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
//Added Sorting to Calculated Field
$dataProvider->setSort([
'attributes' => [
'standing' => [
'asc' => ['standing' => SORT_ASC],
'desc' => ['standing' => SORT_DESC],
'label' => 'Standing',
],
]
]);
我在下面添加了
$query->andFilterWhere(['Standing' => $this->standing]);
但是当我尝试搜索过滤器时,我得到了这个错误:
SQLSTATE [42S22]:未找到列:1054未知列'站立'在' where子句' 正在执行的SQL是:SELECT COUNT(*)FROM
Pricing
WHEREStanding
='降低'
为什么过滤器试图从没有case语句的普通表中获取计数?我该如何解决这个问题,以便我可以使用过滤器?
答案 0 :(得分:2)
我认为您在gridView
或类似内容中使用此查询。 Yii总是首先进行count
查询,以便为视图设置合适的分页。
documentation建议您使用数组,如果您的select
个查询中有任何逗号,那么可能值得尝试,就像这样。您还需要specify the sort differently;
$dataProvider = new \yii\data\ActiveDataProvider([
'query' => Pricing::find()->select([
'*',
'standing' => '(CASE WHEN MyPrice > CompetitorPrice THEN 'Higher' WHEN MyPrice = CompetitorPrice THEN 'Equal' ELSE 'Lower' END)'
]),
'sort' => [
'attributes' => [
'standing' => [
'asc' => ['standing' => SORT_ASC],
'desc' => ['standing' => SORT_DESC],
'default' => SORT_DESC,
'label' => 'Standing'
]
]
]
]);
根据this回答,您还必须将别名声明为模型中的公共变量。那应该为你排序。
public $standing;