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

AndySong's avatar

Query Builder (where and orderBy)

I have a model Thread and Reply, and that is one to many relationship.

so every time I query thread I will have the replyCount with it.

protected static function boot()
    {
        parent::boot();

        static::addGlobalScope('replyCount', function (Builder $builder) {
            $builder->withCount('replies');
        });
    }

so I can do Thread::orderBy('replies_count')->get() no problem.

however when I do Thread::where('replies_count',0)->get() I got the database column not found error.

I am confused that why orderBy did not give me the database column not found error, the where does?

0 likes
3 replies
staudenmeir's avatar
Level 24

You can only access derived columns in the HAVING clause:

Thread::having('replies_count', 0)->get()
AndySong's avatar

@STAUDENMEIR - so orderBy can do both derived columns and database columns, whereas where can only access database columns?

staudenmeir's avatar

Yes. The database evaluates the WHERE clause before the SELECT clause.

Please or to participate in this conversation.