【发布时间】:2021-08-30 16:18:09
【问题描述】:
我正在使用 Laravel 8 构建一个 Web 应用程序,而我经常遇到的一件事是复杂的关系和访问数据。我已经开始阅读 hasManyThrough 关系,但我不相信这是我的场景的正确方法。
旅行推销员使用该应用程序在他们安全到达时签到某个位置。
我有三个主要的表:
-
Locations(他们正在访问的地方), -
Checkins(他们签入数据的存储位置,例如时间), Users
这就是它变得有点复杂的地方,我发现自己无法只见树木不见森林......
- 位置有很多用户,用户有很多位置。已创建多对多数据透视表。
- 地点有很多签到,签到有很多地点。已创建多对多数据透视表。
- 签到有很多用户,用户有很多签到。已创建多对多数据透视表。
因此,它们都是使用belongsToMany 关系创建的。
现在我想做的是访问user 的check in,这样我就可以在我的show.blade.php 上调用类似的东西:
<tbody>
@foreach($location->checkins as $checkin)
<tr>
<td>{{ $checkin->id }}</td>
<td>{{ $checkin->users()->name }}</td> // I'd like to get the users name
<td>{{ $checkin->longitude }}</td>
<td>{{ $checkin->latitude }}</td>
<td>{{ \Carbon\Carbon::parse($checkin->created_at)->format('jS F Y') }}</td>
</tr>
@endforeach
</tbody>
hasManyThrough 关系是我实现这一目标的唯一方法吗?或者我应该让我的控制器更有创意,让用户通过他们自己的收藏来体验?
我当前的Location 控制器如下所示:
public function show(Location $location)
{
$page_title = "Locations";
$page_description = "Event locations.";
return view('pages.admin.locations.show', compact('page_title', 'page_description'))
->with('location' => $location);
}
感谢任何方向或最佳实践建议。
【问题讨论】:
标签: laravel eloquent laravel-8 eloquent-relationship