php - 如何在 laravel 7 中创建 3 个表之间的关系?
问题描述
我在数据库中有三个表。第一个是“bookings”,包含一些列:id、customer_id 等。第二个是“customer”,包含 id、name、email 等。
第三个是“customer_meta”,带有 id、object_id(这是对“customer”表中 id 列的引用)、meta_key 和 meta_value。它包含有关客户的其他数据,例如出生日期、护照号码、性别等。此表中的每一行都是特定客户的不同条目,如下所示:
ID | object_id | 元密钥 | 元值 |
---|---|---|---|
1 | 1 | cf_x4rMBfn3 | 1989 年 10 月 11 日 |
2 | 1 | cf_x4rMBfb5 | 1234567 |
3 | 1 | cf_x4rMB735 | 米 |
我在预订和客户表之间创建了一对多关系。这是我的控制器中的索引函数的代码。
public function index()
{
$bookings = Booking::with('customer')->get();
return view('bookings', [
'bookings' => $bookings,
]);
}
一切运作良好。我可以像这样在刀片文件中显示数据:
<tbody>
@foreach ( $bookings as $booking )
<tr>
<td>{{ $booking->id }}</td>
<td>{{ $booking->start_date }}</td>
<td>{{ $booking->customer->first_name }}</td>
<td>{{ $booking->customer->last_name }}</td>
</tr>
@endforeach
</tbody>
现在我想从“customer_meta”访问数据。我似乎无法弄清楚“bookings”表和“customer_meta”表之间的关系类型。我想通过包含 customer_id 的“预订”显示特定客户的所有行。
解决方案
如果您设置了 customer 和 customer_meta 之间的关系,您应该能够像访问它一样
class Customer extends Model
{
public function customerMeta()
{
return $this->hasMany(App\Models\CustomerMeta::class, 'object_id', 'id');
}
}
$bookings = Booking::with('customer', 'customer.customerMeta')->get();
...
{{ $booking->customer->customerMeta->meta_key }}
如果您想直接从预订记录访问 customer_meta,您可以使用“有一个直通”或“有多个直通”关系,请参阅https://laravel.com/docs/7.x/eloquent-relationships#has-one-through .
这样您就可以直接从预订记录中访问 customer_meta
class Booking extends Model
{
public function customerMeta()
{
return $this->hasOneThrough(App\Models\CustomerMeta::class, App\Models\Customer::class);
}
}
推荐阅读
- wordpress - 摘录wordpress中的音频播放器
- android - 使用 Retrofit + Rx 链接 API 请求
- sql - 使用 SQL Server 将一列中的字符串中的多个值拆分为多列
- c# - 如何在我的正则表达式条件之前立即获得单词?
- java - 通过 Java DIScord Bot 提及任何成员
- base64 - Base64 编码文件显示“GZIP”,但在 Python 中对其进行解码会输出损坏的 HTML
- c - 堆中存储的 calloc 的标头和有效负载信息在哪里?
- android - 安卓工作室。HttpHostConnectException
- pandas - 此版本的 pandas 与 numpy < 1.17.3 不兼容,您的 numpy 版本为 1.16.3。请将 numpy 升级到 >= 1.17.3
- javascript - 如何在现有项目中使用 svelte?