Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

moses's avatar
Level 2

Why `having` only worked on fields that are `group by` on laravel eloquent?

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);

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

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

How can I solve this problem?

0 likes
4 replies
Digitalized's avatar

You can only apply HAVING to columns which appear in GROUP BY or in an aggregate function.

You should be able to use a WHERE and a HAVING clause in the same statement, try just including attributes in your params array which you are grouping by (eg. number)

Otherwise try using a WHERE clause for attributes you are not grouping by (eg. description)

boboboy's avatar

Hello @Digitalized

I have question, when I am use aggregate in eloquent relation like

    $products =  Product::with(['brand', 'category', 'variants'])
        ->filter()
        ->withCount([
            'reviews as rating' => function ($query) {
                $query->select(DB::raw('coalesce(round(avg(rating),1),0)'));
            },
            'reviews as review_count'
        ])
        ->withMin('variants as price', 'price')
        ->active()
        ->sort($request)
        ->between($request)
        ->min($request)
        ->like($request)
        ->simplePaginate(20)
        ->withQueryString()
        ->toArray();

and the scope like

public function scopeBetween($query, $request)
{
    $between = explode(',', $request->get('between'));

    return $query->when($request->has('between'), fn () => $query->havingBetween($between[0], [$between[1], $between[2]]));
}

public function scopeMin($query, $request)
{
    $min = explode(',', $request->get('greater_or_equal'));

    return $query->when($request->has('greater_or_equal'), fn () => $query->having($min[0], '>=', $min[1]));
}

why the error showing no price column?

Please or to participate in this conversation.