Use two foreign keys pointing to the same table and retrieve with one relationship

Posted 1 year ago by oten

I have two tables that describe trades between users


  • id
  • name


  • id
  • user1_id (foreign key to User.id)
  • user2_id (foreign key to User.id)
  • object

What I'm trying to do is to return all trades for a specific user using one Eloquent Relationship. No matter what I have tried I never managed to do something like this:

$user = User::with('trades')->first();

The best result I could achieve was to define two different relationships, for example:

public function trade1 () {
    return $this->hasMany('App\User', 'user1_id');

public function trade2 () {
    return $this->hasMany('App\User', 'user2_id');

and then

$user = User::with(['trade1', 'trade2'])->first();

which of course return two relations (trade1, trade2). Is it possible to combine these two relationships into one?

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.