1
我有一個插入有關訂單的詳細信息的問題。雄辯laravel模型空id編號
型號:
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 user_ID的 p_number 城市 狀態 ...
個ORDER_DETAILS: ID ORDER_ID PROD_ID 量 ...
控制器:
$data = $request->except('_token','submit');
$爲了=新訂單(); $ 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」空,我應該如何正確地得到以填補其ORDER_DETAILS id字段?
我到底應該得到這樣的事情:
Orders:
1
1
+12345678
NY
processing
...
Order_details:
1
1
2
5
-----------
2
1
3
4
-----------
3
1
8
2
-----------
Im做它在我代碼,看上面,我做了大膽 – Batmannn
@Batmannn不,你正在做'$ order = new Order(); $ order-> create($ data);'你的代碼會在'create()'後面返回一個空模型。我的答案中的代碼將返回創建的模型。正如我在另一個問題中所說的,你的架構不好。您應該瞭解多對多關係,並將其用於Order和Model產品模型,並去掉OrderDetails模型。 –