我在插入有关订单的订单详细信息时遇到问题。
楷模:
class Order extends Model
{
protected $fillable = ['user_id','name','surname','fathers_name','phone_number','city','post_office','comment'];
public function user()
{
return $this->belongsTo('App\User');
}
public function orderDetails()
{
return $this->hasMany('App\OrderDetails');
}
}
class OrderDetails extends Model
{
protected $fillable = ['order_id','product_id','amount'];
public function order()
{
return $this->belongsTo('App\Order');
}
public function product()
{
return $this->hasMany('App\Product');
}
}
表格:
订单:
ID
用户身份
p_number
市
状态
...
订单详细信息:
ID
order_id
prod_id
量
...
控制器:
$data = $request->except('_token','submit');
$ order = new Order();
$ order-> create($ data);
$order_details = new OrderDetails();
$cart_content = Cart::content();
$order_content = [];
foreach($cart_content as $key=>$cart_item) {
$order_content[$key]['order_id'] = $order->id;
$order_content[$key]['id'] = $cart_item->id;
$order_content[$key]['qty'] = $cart_item->qty;
$order_content[$key]['price'] = $cart_item->price;
}
dd($order_content);
/*
foreach($order_content as $order_item)
{
$order_details->create($order_item);
}
*/
因此,当我打印$ order_content时,我得到的'order_id'为null,我应该如何正确获取订单ID以便在order_details中填写其字段?
最后我应该得到这样的东西:
Orders:
1
1
+12345678
NY
processing
...
Order_details:
1
1
2
5
-----------
2
1
3
4
-----------
3
1
8
2
-----------
最佳答案
您需要将结果保存到变量中:
$order = (new Order)->create($data);
要么:
$order = Order::create($data);
关于php - Eloquent Laravel模型清空ID,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42442345/