les*_*gar 7 php pivot-table laravel eloquent
我在User和Notification 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的那一行怎么办?有没有办法pivot与where或结合has?可以在没有循环的情况下完成$user->notifications()吗?
您可以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)
| 归档时间: |
|
| 查看次数: |
6045 次 |
| 最近记录: |