Laravel two references to same table

时间:2018-03-25 20:25:52

标签: laravel relationship has-many

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)

2 个答案:

答案 0 :(得分:1)

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;

答案 1 :(得分:0)

Create sender and receiver hasMany relation on your User model and similar belongsTo in your transactions model

User.php

public function transactions(){
return $this->hasMany(Transactions::class);
}

Transactions

public function sender(){
  return $this->belongsTo(User::class, 'sender_id');
}

public function receiver(){
  return $this->belongsTo(User::class, 'receiver_id');
}