pickab00
1 month ago
172
2
Laravel

Where clause in Polymorphic Relationship

Posted 1 month ago by pickab00

I have 2 tables. 1 is the polymorphic table and the other is a simple posts table. Here:

posts:

 - id
 - title
 - detail

viewable:

 - uuid
 - viewable_type
 - viewable_id

and in my model:

//Post.php

public function views() {
      return $this->morphMany(Viewable::class, 'viewable');
}

//Viewable.php

public function viewable() {
        return $this->morphTo();
}

So now I want to get the total count of the items and I am doing this (which works):

$post = Post::find(1);
$post->views()->count(); //which works as expected

What I want to do is to check the UUID and check if the UUID exists in the table. Here is what I tried:

$post->whereHas('views', function($q) {
	$q->where('uuid', 'someuuid')
})->count();

This does not seem to work. And also, I want to take unique items only. So suppose the UUID is repeated in the table. I want to ignore the repeated and if the UUID exists, I want the count of that record as 1 (excluding the repeats)

Please sign in or create an account to participate in this conversation.