我现在正在使用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引用的Pizza资源。但是对于每个订单资源,我的代码都执行2个订单和Pizza的SQL。我只想执行1条sql。如何修复我的代码?
数据库表“订单”已经具有带有“比萨饼”的外键。