我是Laravel Stack的新手,目前正在与Lumen和Eloquent开发API。我需要将Order
模型与它们的OrderLine
一起保存。但是,它没有通过。你能告诉我怎么做吗?
以下是我的模型和控制器设置:
class Order extends Model {
public function orderLines() {
return $this->hasMany('App\OrderLine')
}
}
class OrderLine extends Model {
.....
}
//inside OrdersController method I'm trying to save Order with Order lines received from JSON body
public function create(Request $request)
{
$orderData = $this->validate($request, [
'store' => 'required',
......
'order_status' => 'bail|required|max:20',
'delivery_date' => 'nullable|date',
'customer_id' => 'nullable|numeric',
'order_lines.*.product_id' => 'bail|required|numeric',
'order_lines.*.description' => 'bail|required|max:80',
'order_lines.*.unit_price' => 'bail|required|numeric',
'order_lines.*.discount' => 'bail|required|numeric',
'order_lines.*']);
$order = new Order($orderData);
$order->push(); // This does not save and gives me an error
$order->refresh();
return response()->json($order);
}
//This is the json body provided in the request
{
"store" : "Some Store",
...
"order_lines" : [{
"product_id": 1,
"description": "TU001: Polka dots",
"unit_price": 1000,
"discount": 100,
"units": 2
},
{
"product_id": 2,
"description": "TU002: Polka dots",
"unit_price": 500,
"discount": 0,
"units": 1
}]
}
当我尝试使用save
方法单独保存不带订单行的订单时,它可以工作。但是使用OrderLine
s失败。
有人可以告诉我如何做到这一点。我曾经在CakePHP中做到这一点,但是不确定在Eloquent中是如何做到的。
//使用更多信息进行编辑
在生成的插入sql查询中,我看到orderLines
作为Order
表中的一列。从那开始,它给出了数组到字符串的转换错误。但是实际上插入orderLines
应该在单独的sql查询中。
答案 0 :(得分:3)
public function create(Request $request)
{
$this->validate($request, [
'store' => 'required',
......
'order_status' => 'bail|required|max:20',
'delivery_date' => 'nullable|date',
'customer_id' => 'nullable|numeric',
'order_lines.*.product_id' => 'bail|required|numeric',
'order_lines.*.description' => 'bail|required|max:80',
'order_lines.*.unit_price' => 'bail|required|numeric',
'order_lines.*.discount' => 'bail|required|numeric',
'order_lines.*'
]);
$order = new Order($request->except('order_lines'));
$order->save();
$order->orderLines()->createMany($request->input('order_lines'));
$order->load('order_lines'); //not sure that you need this line
return $order;
}