Laravel Eloquent "Many-to-Many-to-One ?"

250 views Asked by At

My database schema:

user:
    - id
    - email
    ...

notification_user:
    - user_id
    - notification_id

notifications:
    - id
    - channel_id
    - message
    ...

channels:
    - id
    - name
    ...


User Model:

public function notifications()
{
    return $this->belongsToMany('App\Notification');
}


Notification Model:

public function users()
{
    return $this->belongsToMany('App\User');
}


What is the problem: App\User::find(1)->notifications shows all notifications which belongs to this user and it works fine, but I also need to include data from channels table.

<App\Notification #000000004e6906c1000000014ed0d97c> {
   id: 20,
   channel_id: 3,
   message: "...",
   created_at: "2015-05-31 17:37:12",
   updated_at: "2015-06-07 10:37:12",
   pivot: <Illuminate\Database\Eloquent\Relations\Pivot #000000004e690718000000014ed0d97c> {
       user_id: 1,
       notification_id: 20
   }
},

The above is output from tinker. Question is: How to include data from channels table for every notification.

2

There are 2 answers

0
chanafdo On BEST ANSWER

Add a Channel relationship to Notification model.

public function channel()
{
    $this->belongsTo('App\Channel');
}

Then you can load the notifications with channel like below.

App\User::with('notifications', 'notifications.channel')->find(1)
2
Mahozi On

Make a one-to-many relationship between Channel model and Notification model.

Notification Model:

public function users()
{
    return $this->belongsToMany('App\User');
}

public function channel()
{
    return $this->belongsTo('App\Channel');
}

Chanel model:

public function notifications()
{
    return $this->hasMany('App\Notification');
}

And then you can access the channel for each notification.

$channel = $notification->channel;