我正在为电子商务应用程序构建一个API
现在,我陷入了创建秩序的困境
我有以下迁移
订单
Schema::create('orders', function (Blueprint $table) {
$table->id();
$table->string('order_number');
$table->unsignedBigInteger('user_id');
$table->enum('status', ['pending','processing','completed','decline'])->default('pending');
$table->float('grand_total');
$table->integer('item_count');
$table->boolean('is_paid')->default(false);
$table->enum('payment_method', ['cash_on_delivery'])->default('cash_on_delivery');
$table->string('notes')->nullable();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamps();
});
order_items
Schema::create('order_items', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('order_id');
$table->unsignedBigInteger('product_id');
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
$table->foreign('order_id')->references('id')->on('orders')->onDelete('cascade');
$table->float('price');
$table->integer('quantity');
$table->timestamps();
});
产品
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('img');
$table->string('name');
$table->string('desc');
$table->integer('price');
$table->timestamps();
});
这是模特的关系
订单模型
public function items()
{
return $this->belongsToMany(Medicine::class, 'order_item','order_id','product_id')->withPivot('quantity','price');
}
public function user()
{
return $this->belongsTo(User::class);
}
控制器
public function store(Request $request)
{
$order = new Order();
$order->order_number = uniqid('ORD.');
$order->user_id = 1;
$order->item_count = 2;
$order->grand_total = 20;
$order->save();
return response(['message'=>'successful']);
}
现在,我可以成功添加订单了。
但是如何从JSON请求中添加项
例如,通过从Postman发布JSON数据
有什么想法吗?
当前,您存储的是硬式存储,而不是use$request值。 如下所示
public function store(Request $request)
{
$order = new Order();
$order->order_number = uniqid('ORD.');
$order->user_id = $request->user_id;
$order->item_count = $request->item_count;
$order->grand_total = $request->grand_total;
$order->save();
return response(['message'=>'successful']);
}
在你的邮递员通行证的价值像
{
user_id:1;
item_count:2;
grand_total:20;
}