Laravel 5 hasMany relationship on two columns

后端 未结 4 2085
南方客
南方客 2020-11-30 03:13

Is it possible to have a hasMany relationship on two columns?

My table has two columns, user_id and related_user_id.

I want my rela

相关标签:
4条回答
  • 2020-11-30 03:47

    I'd prefer doing it this way:

    public function userRelations()
    {
        return UserRelation::where(function($q) {
            /**
             * @var Builder $q
             */
            $q->where('user_id',$this->id)
                ->orWhere('related_user_id',$this->id);
        });
    }
    
    public function getUserRelationsAttribute()
    {
        return $this->userRelations()->get();
    }
    
    0 讨论(0)
  • 2020-11-30 03:56

    If anyone landed here like me due to google: As neither merge() (as suggested above) nor push() (as suggested here) allow eager loading (and other nice relation features), the discussion is still ongoing and was continued in a more recent thread, see here: Laravel Eloquent Inner Join on Self Referencing Table

    I proposed a solution there, any further ideas and contributions welcome.

    0 讨论(0)
  • 2020-11-30 04:06

    Compoships adds support for multi-columns relationships in Laravel 5's Eloquent.

    It allows you to specify relationships using the following syntax:

    public function b()
    {
        return $this->hasMany('B', ['key1', 'key2'], ['key1', 'key2']);
    }
    

    where both columns have to match.

    0 讨论(0)
  • 2020-11-30 04:12

    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();
    
    0 讨论(0)
提交回复
热议问题