Laravel雄辩的“多对多对一?" [英] Laravel Eloquent "Many-to-Many-to-One ?"

查看:63
本文介绍了Laravel雄辩的“多对多对一?"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据库架构:

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');
}


出了什么问题: App\User::find(1)->notifications显示属于该用户的所有通知,并且工作正常,但我还需要包括channels表中的数据.


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
   }
},

以上内容是修补匠的输出. 问题是:如何为每个通知添加channels表中的数据.

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

推荐答案

Notification模型添加Channel关系.

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)

这篇关于Laravel雄辩的“多对多对一?"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆