Laravel 5 hasMany relationship on two columns

后端 未结 4 2104
南方客
南方客 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();
    }
    

提交回复
热议问题