Mwatha Kinyua
Mwatha Kinyua

Reputation: 19

Eloquent Relationship. Has Many relation with different keys

Background

I have a model, Contract that belongs to the User model through two keys, user_id and recipient_id. How would I be able to query all the contracts for a user using $user->contracts keeping the two key into consideration.

\App\Contract model has this

$protected $fillable = [
   ...
   'user_id',
   'recipient_id',
   ...
];

public function user ()
{
   return $this->belongsTo(User::class);
}
public function recipient()
{
   return $this->belongsTo(User::class, 'recipient_id', 'id');
}

\App\User model has this

public function contracts ()
{
  return $this->hasMany(Contract::class);
}

To get the user contracts, I have to do this

$contracts = Contract::where('user_id', $user->id)
   ->orWhere('recipient_id', $user->id)
   ->get();

What I would like is something like this. \App\Contract

public function user () {
  return $this->belongsTo([User::class, User::class], ['user_id', 'recipient_id']);
}

I am aware of https://github.com/staudenmeir/eloquent-has-many-deep and it doesn't solve my problems.

How do I go about it?

Upvotes: 0

Views: 39

Answers (1)

Mwatha Kinyua
Mwatha Kinyua

Reputation: 19

I couldn't find a way, so, I ended doing this in ContractController.php

public function index()
    {
        $user = Auth::user();

        if ($user->isAdmin()) {
            return Contract::latest()->get();
        }

        $contracts = Contract::where('user_id', $user->id)
            ->orWhere('recipient_id', $user->id)
            ->get();

        return $contracts;
    }

Upvotes: 1

Related Questions