Framework: Eloquent withCount having is working fine on MySql, but generates an error on Postgres

Created on 4 Oct 2019  路  4Comments  路  Source: laravel/framework

  • Laravel Version: 6.0
  • PHP Version: 7.3
  • Database Driver & Version: psql

Description:

The following Eloquent query is working fine on mysql, but is generating an error "column products_count does not exists" in postgresql

ProductCategory::withCount('products')->having('products_count', '>' , 0)->get();

Steps To Reproduce:

Two models ProductCategory (has many) and Product (belongs to)
The query is a way to retrieve only categories that has products.

needs more info

Most helpful comment

The SQL standard doesn't allow HAVING clauses to access derived columns like products_count. MySQL is less strict about that.

There are multiple solutions, a subquery is one of them:

$query = ProductCategory::withCount('products');

ProductCategory::fromSub($query, 'alias')
    ->where('products_count', '>', 0)
    ->get();

If you don't need the count in the results, you can also use has():

ProductCategory::has('products')->get();

All 4 comments

Not sure what's going on here. Hopefully someone can help out.

@gncvalente please paste the SQL query generated (for both MySQL and PgSQL), thanks

The SQL standard doesn't allow HAVING clauses to access derived columns like products_count. MySQL is less strict about that.

There are multiple solutions, a subquery is one of them:

$query = ProductCategory::withCount('products');

ProductCategory::fromSub($query, 'alias')
    ->where('products_count', '>', 0)
    ->get();

If you don't need the count in the results, you can also use has():

ProductCategory::has('products')->get();

Great thankyou !

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Anahkiasen picture Anahkiasen  路  3Comments

SachinAgarwal1337 picture SachinAgarwal1337  路  3Comments

fideloper picture fideloper  路  3Comments

felixsanz picture felixsanz  路  3Comments

Fuzzyma picture Fuzzyma  路  3Comments