Skip to content
Advertisement

Laravel using where clause on a withCount method

I am trying to do a where clause on withCount method of laravel’s eloquent query builder using this piece of code.

and this code is giving me this error.

SQLSTATE[42S22]: Column not found: 1054 Unknown column ‘upvotes_count’ in ‘where clause’ (SQL: select , (select count() from upvotes where upvotes.upvoteable_id = posts.id and upvotes.upvoteable_type = AppPost) as upvotes_count from posts where upvotes_count > 5)

So from what I can guess is that upvotes_count isn’t selected and hence the column is not being found, BUT if I execute this piece of code.

Then I am getting this output.

Which basically means that upvotes_count is being selected, hence i am really confused about how to solve this problem.

(More options that I tried so far are given below with the respective error associated to it.)

error.

SQLSTATE[42S22]: Column not found: 1247 Reference ‘upvotes_count’ not supported (forward reference in item list) (SQL: select , (select count() from upvotes where upvotes.upvoteable_id = posts.id and upvotes.upvoteable_type = AppPost and upvotes_count > 5) as upvotes_count from posts where id = 1)

code.

AND

error.

SQLSTATE[42S22]: Column not found: 1054 Unknown column ‘upvotes_count’ in ‘where clause’ (SQL: select * from posts where id = 1 and upvotes_count > 5)


I just want to use where clause on a count() method which is in a relationship with a parent model.

Advertisement

Answer

You can achieve requested result by using:

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement