laravellaravel-5modelrelationships

Laravel Relationship with OR case


Assume I have a User model, and also I have Couple model which forms of 2 users, father_id and mother_id which are essentially user_ids

On User model, I have

public function kids() {
    return $this->hasMany('App\Kid', 'father_id');
}

However, I want to check if user_id is either father_id or mother_id, return the related Kid model.

Is there a way to achieve it with a single relationship? What is the proper way of handling this scenario, so I can use $user->kids that would check for both cases?


Solution

  • There is a way, but you wouldn't typically use it to "check" if there are related models.

    If you have a field that determines if the model is representing a father or mother, such as is_father, you could do:

    public function kids()
    {
        return ($this->is_father)
            ? $this->hasMany(Kid::class, 'father_id')
            : $this->hasMany(Kid::class, 'mother_id');
    }
    

    Essentially, the relationship method MUST return a relationship instance. But you can do logic before you return this.

    NOTE: The relationship is cached, so even if the is_father value changes in the same thread run, it will utilize the same relationship that it did before. This can cause unwanted bugs.