Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel two references to same table

I have a transactions tables with sender_id and receiver_id columns which are both references of user.

now, I want to create a hasMany relationship for the user. (all user's transaction, be it,received or sent)

like image 923
Emmanuel Sarpong Avatar asked Jun 03 '26 06:06

Emmanuel Sarpong


1 Answers

You can create one relationship for all transactions:

public function transactions() {
    return $this->hasMany(Transaction::class, 'sender_id')
        ->orWhere('transactions.receiver_id', $this->id);
}

But that's not a very elegant solution because it breaks eager loading.

The better solution is using two relationships and then merging them:

public function senderTransactions() {
    return $this->hasMany(Transaction::class, 'sender_id');
}

public function receiverTransactions() {
    return $this->hasMany(Transaction::class, 'receiver_id');
}

public function getTransactionsAttribute() {
    return $this->senderTransactions->merge($this->receiverTransactions);
}

Then use it like this:

$transactions = $user->transactions;
like image 69
Jonas Staudenmeir Avatar answered Jun 05 '26 02:06

Jonas Staudenmeir