Давайте проиллюстрируем это на примере упрощенная ситуация:
Модели:
Код: Выделить всё
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,
];
}
}
Код: Выделить всё
/**
* @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
];
}
}
Код: Выделить всё
ReportCountryResource
Код: Выделить всё
CountryResource
Есть ли способ это сделать? Сейчас я создаю кучу ресурсов для сводных моделей, которые мне на самом деле не нужны :/
Подробнее здесь: https://stackoverflow.com/questions/790 ... -resources