flyingcar10
flyingcar10

Reputation: 3

Laravel multiple user id tables

I'm pretty new to laravel and have a really basic question related to relationships.

Here is an example of my question:

I have a migration called money_transfers. The migration contains the following things:

  1. user_id (transfer sent by)
  2. sentTo_id (transfer sent to)
  3. amount
  4. sent_at

BOTH user_id and sentTo_id refer to a User ID.

Now, what I want to do is the following:

Fetch the user the money was sent TO the same way as the user the money was sent BY. Just like in the example below:

$transfer->sentTo->name

or

$transfer->sentTo->id

You get what I mean. Thanks in advance :)

Upvotes: 0

Views: 710

Answers (1)

Makdous
Makdous

Reputation: 1433

If you defined your foreign keys correctly in your migration table, Then it's just a matter of defining the right relationship:

class MoneyTransfer extends Model
{

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



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

This way you can access the receiver attribute like this:

$transfer->sentTo->name;

And the sender attribute like this:

$transfer->sentBy->name;

Upvotes: 1

Related Questions