【问题标题】:Laravel 4 collecting data from relationshipLaravel 4 从关系中收集数据
【发布时间】:2015-08-11 04:51:02
【问题描述】:

在我的应用程序中,我有一个 Notifications 表和一个 Users 表,一个通知可以属于许多用户,所以在我的通知类中,我有以下内容,

public function user()
{
    return $this->belongsToMany('User');
}

在我的数据库中,我还有一个名为 notification_user 的表,它位于我的 notifications 表旁边。 notification_user 表有以下几行,

notification_id、user_id、is_read、created_at、updated_at

我正在运行以下代码来返回特定用户的通知,

$notifications = Notification::whereHas('user', function($q){
        $q->where('user_id', '=', 101);
})->get();

我发现的问题是,这不会从我迫切需要的notification_user 表中返回 is_read 属性!我已经尝试添加,

$notification->load('user') 在查询之后,但这只是将用户数据添加为对象。

是否也可以获取关系表数据?

【问题讨论】:

    标签: php mysql laravel orm eloquent


    【解决方案1】:

    你需要在你的关系中添加一些额外的东西来告诉 laravel 从数据透视表中提取额外的数据。 (不要忘记在您关系中的其他模型上也这样做)

    public function user()
    {
        return $this->belongsToMany('User')->withPivot('is_read');
    }
    

    然后,您的模型上应该有一个->pivot 属性可用,该属性具有is_read 属性。 (例如:$notification->pivot->is_read)这在文档 http://laravel.com/docs/5.0/eloquent#working-with-pivot-tables

    中有简要介绍

    如果你已经有了用户ID,只是为了方便你自己,你不能只使用它们之间的关系吗?

    $user = User::find(101);
    
    foreach($user->notifications as $notifications)
    {
        if ($notification->pivot->is_read === false)
        {
            // Notification is unread, lets do something
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-16
      • 1970-01-01
      • 2020-02-09
      • 1970-01-01
      • 2014-01-26
      相关资源
      最近更新 更多