Laravel:如何通过键 id 获取单个枢轴行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28363493/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 10:51:08  来源:igfitidea点击:

Laravel: How to get single pivot row by key id

phplaraveleloquentpivot-table

提问by lesssugar

I have a many-to-many relation set on my Userand NotificationEloquent models. This way I can access the pivot table - user_notifications- as follows:

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

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

This will give me all created_atfield values from the pivot table, for the user of ID = 1.

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

What if I need only onepivot row, let's say the one with notification_id = 2? Is there a way to combine pivotwith whereor has? Can it be done without looping through $user->notifications()?

如果我需要一个枢轴行,假设是Notification_id = 2 的那个行呢?有没有办法pivotwhereor结合has?可以不循环完成$user->notifications()吗?

回答by lukasgeiter

You can use a whereclause on the relationship:

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

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

回答by AsDh

You can also directly use findmethod.

也可以直接使用find方法。

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

回答by antirealm

I've been dealing with this, and lukasgeiter's answer is fine, until the weird case where you want to find a pivot row by id(if you set up a $table->increments('id')column on the pivot table. I do this sometimes, but a better solution is to use a dedicated model for the relationship (Defining Custom Intermediate Table Models@ https://laravel.com/docs/5.6/eloquent-relationships)

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

What you can do in this strange case:

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

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

You'll have to include withPivot('id')in your relationship method in the model. i.e.

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

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