我有一个相当常见的设置 - 2 个主要模型和 1 个枢轴以及有关它们关系的附加信息。我正在使用 Laravel API 资源,它们工作得很好,但我无法找到一种方法来显示数据而不需要显示数据透视数据。
我们以简化的情况来说明:
型号:
class Report extends BaseModel
{
public function reportCountries(): HasMany
{
return $this->hasMany(ReportCountry::class, 'report', 'id');
}
}
class ReportCountry extends BaseModel
{
public function report(): BelongsTo
{
return $this->belongsTo(Report::class, 'report', 'id');
}
public function countryEntity(): BelongsTo
{
return $this->belongsTo(Country::class, 'country', 'id');
}
}
class Country extends BaseModel
{
protected $table = 'countries';
}
控制器:
class ReportsController
{
public function show(int $id): ReportResource
{
$report = Report::with(['reportCountries.countryEntity'])->findOrFail($id);
return new ReportResource($report);
}
}
最后是资源:
/**
* @mixin Report
*/
class ReportResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'countries' => ReportCountryResource::collection($this->whenLoaded('reportCountries')), // I'd love to use CountryResource here instead
// bunch of other data
];
}
}
/**
* @mixin ReportCountry
*/
class ReportCountryResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'id' => $this->id, // I don't really need to show this, I'm interested only in CountryResource below:
'country' => new CountryResource($this->whenLoaded('countryEntity')),
];
}
}
/**
* @mixin Country
*/
class CountryResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'title' => $this->title,
];
}
}
我想做的是忽略
ReportCountryResource
并直接在 CountryResource
中加载 ReportResource
,如下所示:
/**
* @mixin Report
*/
class ReportResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'countries' => CountryResource::collection($this->whenLoaded('reportCountries.countryEntity')),
// bunch of other data
];
}
}
但是当我尝试以这种方式加载时,
CountryResource
显示的是来自枢轴 (ReportCountryResource
) 的数据,而不是来自主模型 (CountryResource
) 的数据。
有办法做到这一点吗?我现在正在为枢轴模型创建大量资源,但我并不真正需要:/
只需进行一些小更改,您的代码就应该可以工作,不需要数据透视资源。
控制器:
class ReportsController
{
public function show(int $id): ReportResource
{
$report = Report::with(['reportCountries'])->findOrFail($id);
return new ReportResource($report);
}
}
class ReportResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'countries' => CountryResource::collection($this->whenLoaded('reportCountries')),
// bunch of other data
];
}
}