我相信我需要的答案就在某个地方here但我不知何故无法弄清楚我的代码有什么问题。
我正在尝试在创建订单后创建订单详细信息表。 所以我在这里将数据从 vue 发布到端点。
createOrder: function() {
this.$http.post('/api/orders', {
customer_id: this.form.customer.id,
items: _.map(this.cart, function(cart){
return {
//these are the only values I need from the each item in the cart.
product_id: cart.id,
quantity: cart.quantity,
price: cart.price
}
})
}).then(function(response) {
let responseBody = response.body;
this.$set('cart', []);
this.form.customer = {};
});
然后在 Controller 的存储方法中,我想收集数据,创建订单,使用购物车中的所有商品创建 order_details 表。
public function store(Request $request)
{
$items = $request->input('items');
$staff = $request->user()->id;
$customer = $request->input('customer_id');
$status_id = 1;
$order = new Order();
$order->user_id = Auth::user()->id;
$order->id_statuses = $status_id;
$order->id_customers = $customer;
//save order
$order->save();
foreach($items as $item){
$order_detail = new OrderDetail();
$order_detail->order_id = $order->id;
$order_detail->id_products = $item->product_id;
$order_detail->quantity = $item->quantity;
$order_detail->price = $item->price;
//save order detail
$order_detail->save();
}
return response()->json($order);
}
在回溯中,所有值都返回 null,因此我收到了数据库错误。我敢打赌,我实际上并没有获得这些元素或正确访问那里的属性。
如果有帮助的话,这是有效负载的镜头。我也愿意接受有关发布数据的更好方法的建议,以便更容易使用,因为我对这两个框架都是新手。
错误消息:
SQLSTATE[23000]: Integrity constraint violation: 1048
Column 'id_products' cannot be null (SQL: insert into `order_details`
(`order_id`, `id_products`, `quantity`, `price`, `updated_at`,
`created_at`) values (78, , , , 2016-12-30 17:18:04, 2016-12-30 17:18:04))
最佳答案
id_products
的值未出现在 $items 变量中。
尝试使用
$items = $request->items;
您需要提供 id_products
的值,至少为空白
或
您应该输入默认值
$table->integer('id_products')->default(0);
要更改现有列,请使用此
$table->integer('id_products')->default(0)->change();
在 Laravel 5.3 中,如果没有任何默认值,则不能将此项保留为空
关于php - SQLSTATE[23000] : Integrity constraint violation: 1048. 将数据从 vue 发布到 laravel Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41396219/