Laravel:如何通过密钥id获得单个数据透视表行

les*_*gar 7 php pivot-table laravel eloquent

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

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

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

如果我需要一个数据透视表行,让我们说一个带有notification_id = 2的那一行怎么办?有没有办法pivotwhere或结合has?可以在没有循环的情况下完成$user->notifications()吗?

luk*_*ter 8

您可以where在关系中使用一个子句:

$notification = $user->notifications()->where('notification_id', 2)->first();
echo $notification->pivot->created_at;
Run Code Online (Sandbox Code Playgroud)


小智 5

您也可以直接使用find方法。

$notification = $user->notifications()->find(2);
echo $notification->pivot->created_at;
Run Code Online (Sandbox Code Playgroud)