Сейчас я пишу простое приложение для заказа пиццы с помощью Laravel.
Вот моя текущая кодировка:
class Order extends Model {
protected $table = 'orders';
protected $primaryKey = 'id';
public $timestamps = false;
protected $fillable = ['pizzaid', 'date'];
}
class Order extends JsonResource {
public function toArray($request) {
return [
'id' => $this->id,
'pizzaid' => $this->pizzaid,
'date' => $this->date,
'pizzadata' => PizzaResource::collection(Pizza::where('id', $this->pizzaid)->get()),
];
}
}
class Pizza extends Model {
protected $table = 'pizzas';
protected $primaryKey = 'id';
public $timestamps = false;
protected $fillable = ['name', 'price', 'detail'];
}
class Pizza extends JsonResource {
public function toArray($request) {
return [
'id' => $this->id,
'name' => $this->name,
'price' => $this->price,
'picture' => $this->picture,
'detail' => $this->detail,
];
}
}
Как вы можете видеть здесь, каждый ресурс заказа должен показывать ресурс пиццы, на который ссылается pizzaid. Но для каждого ресурса заказа мой код выполняет 2 sqls заказа и пиццы. Я хочу выполнить только 1 кв. Как я могу исправить свой код?
БД «Заказы» уже имеет внешний ключ с «пиццами».