【问题标题】:Laravel - How to get data from a table related with pivot tableLaravel - 如何从与数据透视表相关的表中获取数据
【发布时间】:2018-05-06 19:40:36
【问题描述】:

我有notifications 表的这个模型:

class Notification extends Model
{
    public function users()
    {
        return $this->belongsToMany(User::class, 'notification_user', 'notification_id', 'user_id');
    }
}

控制器中的这个方法用于从notifications 获取数据,其中notifications 的id 与名为notification_user 的数据透视表相关:

$myNotifications = DB::table('notification_user')
            ->join('notifications', 'notifications.id', 'notification_user.notification_id')
            ->where('notification_user.user_id', $userId)
            ->where('notification_user.seen', 0)
            ->get();

$myNotifications 的结果是正确的,但我想使用Model 及其关系而不是DB。

如何获取notifications 中的所有记录,其中每个通知都与用户看不到的特定用户相关。

【问题讨论】:

    标签: laravel pivot pivot-table


    【解决方案1】:

    您需要在关系中添加->withPivot('seen'):

    public function users()
    {
        return $this
            ->belongsToMany(User::class, 'notification_user', 'notification_id', 'user_id')
            ->withPivot('seen');
    }
    

    那么你可以这样做:

    Notification::whereHas('users', function ($q) use ($userId) {
        $q->where('id', $userId)->where('seen', 0);
    })->get();
    

    为避免加入用户,您的另一个选择是whereExists:

    Notification::whereExists(function ($q) use ($userId) {
        $q
            ->selectRaw(1)
            ->table('notification_user')
            ->whereRaw('notifications.id = notification_user.notification_id')
            ->where('user_id', $userId)
            ->where('seen', 0);
    })->get();
    

    应该仍然更高效,但不会更优雅。

    【讨论】:

    • 难道没有其他方法不让我们自己参与到用户模型中,只从通知及其数据透视表中获取结果吗?
    • 我很确定没有。不过,您可以将 whereExists 与原始子查询一起使用。
    【解决方案2】:

    您必须在 User 模型中定义与 notifications 相同的关系,然后:

    $notifications = User::where('id', $user_id)->notifications()->where('seen', 0)->get();
    

    【讨论】:

    • 我不想从与用户表相关的用户模型中获取任何东西,而只想从notifications 和notification_user 中获取任何信息。
    【解决方案3】:

    您可以使用 with 关键字在控制器内部进行预加载。 就像如果您在模型中定义了任何关系,只需在 eloquent 中的 get() 语句之前添加一个 with('modelRelation') 即可。

    快乐编码。

    【讨论】:

      猜你喜欢
      • 2020-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多