Laravel 5 hasMany relationship on two columns

I don’t think it’s possible to do exactly what you are asking.

I think you should treat them as separate relationships and then create a new method on the model to retrieve a collection of both.

public function userRelations() {
    return $this->hasMany('App\UserRelation');
}

public function relatedUserRelations() {
    return $this->hasMany('App\UserRelation', 'related_user_id');
}

public function allUserRelations() {
    return $this->userRelations->merge($this->relatedUserRelations);
}

This way you still get the benefit of eager loading and relationship caching on the model.

$cause = Cause::with('donations.user.userRelations', 
        'donations.user.relatedUserRelations')
    ->where('active', 1)->first();

$userRelations = $cause->donations[0]->user->allUserRelations();

Leave a Comment