Как возвращать определенные поля из связанной таблицы в Laravel 8
Связь установлена через hasOne. Есть такой код:
$flights_to = Flights::where('from_id', $airports_fromid)->with('airports_from')->first();
return response()->json($flights_to, 200);
Который возвращает такой результат:
{
"id": 1,
"flight_code": "FP2100",
"from_id": 2,
"to_id": 1,
"time_from": "08:35:00",
"time_to": "10:05:00",
"cost": 10500,
"created_at": null,
"updated_at": null,
"airports_from": {
"id": 2,
"city": "Moscow",
"name": "Sheremetyevo",
"iata": "SVO",
"created_at": null,
"updated_at": null
}
}
Как сделать так, чтобы возвращались не все поля, а только определенные, например перечислить все кроме "created_at" и "updated_at"?
Ответы (2 шт):
Автор решения: m m
→ Ссылка
Может помочь метод select():
$flights_to = Flights::select(
'id',
'flight_code',
'from_id',
'to_id',
'time_from',
'time_to',
'cost',
'airports_from'
)
->where('from_id', $airports_fromid)
->with('airports_from')
->first();
Детальнее о методе здесь: https://laravel.com/docs/8.x/queries#select-statements
Автор решения: IndianCoding
→ Ссылка
Такие задачи лучше решать при помощи JSON-ресурсов (https://laravel.com/docs/8.x/eloquent-resources).
$flight = Flights
::where('from_id', $airports_fromid)
->with('airports_from')
->first();
return new FlightResource($flight);
Сам класс:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class FlightResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'flight_code' => $this->flight_code,
'from_id' => $this->from_id,
'to_id' => $this->to_id,
'time_from' => $this->time_from,
'time_to' => $this->time_to,
'cost' => $this->cost,
'airports_from' => [
'id' => $this->airports_from->id,
'city' => $this->airports_from->city,
'name' => $this->airports_from->name,
'iata' => $this->airports_from->iata,
]
];
}
}