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

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

我的数据库模式:

user:
    - id
    - email
    ...

notification_user:
    - user_id
    - notification_id

notifications:
    - id
    - channel_id
    - message
    ...

channels:
    - id
    - name
    ...


用户模型:

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


通知模型:

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


问题是什么: App\User::find(1)->notifications 显示属于该用户的所有通知并且工作正常,但我还需要包含来自 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
   }
},

以上是tinker的输出。 问题是: 如何为每个通知包含来自 channels table 的数据。

Channel 模型和 Notification 模型之间建立一对多关系。

通知模型:

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

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

香奈儿模特:

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

然后您可以访问每个通知的频道。

$channel = $notification->channel;

Notification 模型添加 Channel 关系。

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

然后您可以使用如下渠道加载通知。

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