【问题标题】:Laravel: How to get single pivot row by key idLaravel:如何通过键 id 获取单个枢轴行
【发布时间】:2015-04-06 11:03:42
【问题描述】:

我在 UserNotification Eloquent 模型上设置了多对多关系。这样我可以访问数据透视表 - user_notifications - 如下:

$user = User::find(1);
foreach ($user->notifications() as $n) {
    echo $n->pivot->created_at;
}

这将为 ID = 1 的用户提供数据透视表中的所有 created_at 字段值。

如果我需要只有一个枢轴行,假设是 notification_id = 2 的那一行,该怎么办?有没有办法将pivotwherehas 结合起来?不循环$user->notifications()可以做到吗?

【问题讨论】:

    标签: php laravel eloquent pivot-table


    【解决方案1】:

    您可以在关系上使用where 子句:

    $notification = $user->notifications()->where('notification_id', 2)->first();
    echo $notification->pivot->created_at;
    

    【讨论】:

    • 完美运行。谢谢!
    【解决方案2】:

    也可以直接使用find方法。

    $notification = $user->notifications()->find(2);
    echo $notification->pivot->created_at;
    

    【讨论】:

      【解决方案3】:

      我一直在处理这个问题,lukasgeiter 的回答很好,直到你想通过 id 找到一个枢轴行的奇怪情况(如果你在数据透视表。我有时会这样做,但更好的解决方案是为关系使用专用模型(定义自定义中间表模型 @https://laravel.com/docs/5.6/eloquent-relationships

      在这种奇怪的情况下你可以做什么:

      $notification = $user->notifications()->having('pivot_id', 2)->first();
      echo $notification->pivot->created_at;
      

      您必须在模型的关系方法中包含withPivot('id')。即

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-14
        • 1970-01-01
        • 2019-07-24
        • 2021-10-02
        • 2017-04-27
        • 2021-12-28
        • 1970-01-01
        • 2015-06-12
        相关资源
        最近更新 更多