How to group polymorphic relationship in Laravel?

Viewed 39

I have a polymorphic table/class but I wanted to group the relationship. I tried doing whereHasMorph but it still returns all types of relationship. I am not sure if I should be using morphTo here?

Example code:

class Image extends Model
{
    public function animal()
    {
        return ??$this->morphTo()??; // How do I limit this to only relate to Dog and Dragon classes?
    }

    public function user()
    {
        return ??$this->morphTo()??; // How do I limit this to only relate to User?
    }

}
 
class Dog extends Model
{
}

class Dragon extends Model
{
}
 
class User extends Model
{
}

Expected behaviour:

  • If I have image related to dog and I call image->user it should return null;
  • If I have image related to dragon and I call image->animal it should return the dragon model;
  • If I have image related to user and I call image->animal it should return null; And so on...
0 Answers
Related