Search code examples
laravelrelationshiphas-many

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)


Solution

  • 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;