Search code examples
laraveleager-loading

Laravel Define foreign key in relationship according to column value


I'm having these relationships in my event Mode

public function invited()
    {
        return $this->belongsTo('App\Models\User', 'invitee');
    }

        public function senter()
    {
        return $this->belongsTo('App\Models\User', 'invitor');
    }

Table will be having feild "invitee,invitor and organiser". My requirement is to have a method users() where foreign key for belongsTo will be "invitee" if "organiser" != "invitee" else foreign key should be invitor

Thanks in advance!!!


Solution

  • Thanks, @Augusto Moura, but I have found another solution and it's actually not the best one, but works for me, this way I can call users from event model, and also in call users as a nested relation.

        public function users()
    {
        return $this->hasMany('App\Models\Invitation', 'round_id')
            ->select('users.*', 'round_invitations.round_id', 'round_invitations.accept_status', 'round_invitations.reservation', 'round_invitations.id as request_id', 'users.id as user_id')
            ->join('users', function ($join) {
                $join->on('users.id', '=', 'round_invitations.invitee')->whereColumn('users.id', 'round_invitations.invitee');
                $join->orOn('users.id', '=', 'round_invitations.invitor')->whereColumn('users.id', 'round_invitations.invitor');
    
            })->where(function ($query) {
            $query->where('accept_status', 1)->orWhere('reservation', 1);
        })->where('accept_status', '!=', 2)
            ->groupBy('round_invitations.id')
            ->whereColumn('users.id', '!=', 'organiser_id')
            ->groupBy('user_id')
            ->distinct('users.id');
    }
    
    Usage example: Event::with('user')->find(2);
    Another example: Organiser::with('Events.user')->find(2);