我有 3 张桌子合同、详细信息和额外内容。
每个合约都有一个详细信息,其中的外键名为
contractId
,位于 details
表中。
每个细节都有 5 列,来自名为 Color 的额外表,... 我在合约模型中定义了一个 hasOne 关系,在详细模型中定义了一个属于关系,该关系工作正常。
我定义了一个关系,这样我就可以通过详细模型详细获取每个合约的颜色:
public function carColor(): BelongsTo
{
return $this->belongsTo(Extra::class, "ColorCode", "id")->where('type', Extra::COLOR->value);
}
在我的函数中,我编写此代码是为了检索合同模型及其详细信息,并且我加载了额外的内部详细信息,但结果我只是得到了 id 而不是名称:
return ThirdPartyContract::where('id', $id)
->with(['detail' => function ($query) {
$query->with(['carColor' => function ($query) {
$query->select('name');
}]);
}])
->with('people')
->get();
为什么不简单地使用多对多的颜色表,并且颜色表将包含颜色的 ID、名称和类型?这是一个简单的重构,但无论如何,您应该从 Extra 模型(表)中获取 id 和 name:
return ThirdPartyContract::where('id', $id)
->with(['detail' => function ($query) {
$query->with(['carColor' => function ($query) {
// Select the necessary columns from the 'extra' table
// You can add more columns if you want, it's important to have id so you can fetch data from the related tables
$query->select('id', 'name');
}]);
}])
->with('people')
->get();