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

beli0135's avatar

Relation in Class, need more complex query

I have a class that is a comment for a post. they have relationship and it works. Inside POST class:

 public function articleComments()
{
   return $this->hasMany(ArticleComment::class,'ACM_cdiPost','id')
        ->orderBy('updated_at','DESC');
}

So far so good. However, I really need more complex query (in sense of not to present muted or blocked users) which is no problem and I use that SQL in another controller. Problem I am facing is how to do this? In class or to make some controller function and call it somehow from blade file?

0 likes
4 replies
johnsc's avatar
johnsc
Best Answer
Level 1

If the muted or blocked is a flag on the user, you can do something like:

$model->articleComments()->whereDoesntHave('user', function (Builder $query) {
    $query->where('muted', 1)->orWhere('blocked', 1);
})->get();
1 like
beli0135's avatar

Sure. Something like this, where clause.

 $whr =  '(posts.user_id not in (select URR_CdiUserRelated from user_relations where URR_CdiUser = '.$user_id.' and (URR_isMuted = 1 or URR_isBlocked = 1)) ' . 
            ' OR posts.user_id not in (select URR_CdiUser from user_relations where URR_CdiUserRelated = '.$user_id.' and URR_isBlocked = 1 ))' . 
            $nsfwWhere . ' and posts.tweet is not null';
beli0135's avatar

It actually helped me make Where clause and then

return $this->hasMany(ArticleComment::class,'ACM_cdiPost','id')->whereRaw($whr)->orderBy('updated_at','DESC');

Please or to participate in this conversation.