为什么“拥有"仅在laravel雄辩的“分组依据"字段上起作用? [英] Why `having` only worked on fields that are `group by` on laravel eloquent?

查看:68
本文介绍了为什么“拥有"仅在laravel雄辩的“分组依据"字段上起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的脚本laravel雄辩如下:

My script laravel eloquent like this :

$query = $this->item->select('a.*','b.attribute_code')
    ->from('items as a') 
    ->join('attr_maps as b','b.number','=','a.number')
    ->groupBy('a.number');

foreach($param as $key => $value) {
    $query = $query->having($key, '=', $value);
}

$query = $query->paginate(10);

我的$ param是动态的.它可以改变

My $param is dynamic. It can change

如果$paramarray('number'=>'1234'),则它起作用.没有错误

If $param is array('number'=>'1234'), it works. No error

如果$paramarray('description'=>'test'),则存在错误:Unknown column 'description' in 'having clause'

If $param is array('description'=>'test'), there exist error : Unknown column 'description' in 'having clause'

我尝试了表格项目中的所有字段.仅数字字段有效.显然是因为数字字段是分组依据

I tried all fields in the table items. Only the number field works. Apparently because the number field is group by

如果使用having,如何使items表中的所有字段起作用?

How can I make all field in the items table works if using having?

推荐答案

SELECT语句中使用HAVING子句为一组行或集合指定过滤条件. HAVING子句在SELECT之后执行,因此,如果将HAVING应用于不在group by或不在aggregate函数中的列,则它将在哪里工作,这是没有用的,因为select子句已经存在被执行.而且我认为仅因为这种雄辩就可能引发异常,但是不确定.

The HAVING clause is used in the SELECT statement to specify filter conditions for a group of rows or aggregates. The HAVING clause executed after SELECT, so if you apply HAVING on columns which is not in group by or not in aggregate function then it will work as where, which is no use because select clause is already executed. And i think just because of that eloquent may throw exception, not sure though.

您可以做什么,检查param键是否在group by字段中,然后应用(如果没有),然后将其添加为where条件.

What you can do, check your param key if it is in group by fields then apply having if not then add it as where condition like this.

$query = $this->item->select('a.*','b.attribute_code')
    ->from('items as a') 
    ->join('attr_maps as b','b.number','=','a.number')
    ->groupBy('a.number');

foreach($param as $key => $value) {
    if($key== 'number'){
        $query = $query->having($key, '=', $value);
    }else{
        $query = $query->where($key, '=', $value);
    }
}

您可以在此处查看地点与住所

这篇关于为什么“拥有"仅在laravel雄辩的“分组依据"字段上起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆