Question: How to select count and use where with Laravel's fluent query builder?

Question

How to select count and use where with Laravel's fluent query builder?

Answers 2
Added at 2016-12-26 12:12
Tags
Question

in my case

$products = $products->select(array('products.*', \DB::raw('COUNT(extra_fields.price) as price_count')))->leftJoin('extra_fields', 'products.id', '=', 'extra_fields.item_id')
                    ->where('item_type', 'App\Models\Product')
                    ->whereRaw("price = '0'")
                    ->whereRaw("price_count = 1")
                    ->groupBy('item_id')
                    ->groupBy('price')

                ;

when i want to use { price_count } in where or whereRaw i got :

Column not found: 1054 Unknown column 'price_count'

price_count just only work on this way :

->orderBy('price_count')

how can i use price_count on where or whereRaw ?

any advice ?

Answers to

How to select count and use where with Laravel's fluent query builder?

nr: #1 dodano: 2016-12-26 12:12

You can't use summary function value as you want, instead of "where" you can use in "having".

Hope this will help you.

nr: #2 dodano: 2016-12-26 14:12

You can use havingRaw as:

->havingRaw('price_count = 1')

OR

->having('price_count', '=', 1)

OR

The havingRaw method may be used to set a raw string as the value of the having clause.

->havingRaw('COUNT(extra_fields.price) = 1')
Source Show
◀ Wstecz