简体   繁体   English

雄辩的laravel模型空id

[英]Eloquent laravel models empty id

I have a problem with inserting order details about order. 我在插入有关订单的订单详情时遇到问题。

Models: 楷模:

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');

    }


}

Tables: 表:

Orders: id user_id p_number city status ... 订单:id user_id p_number城市状态...

Order_details: id order_id prod_id amount ... Order_details:id order_id prod_id amount ...

Controller: 控制器:

$data = $request->except('_token','submit');

$order = new Order(); $ 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);

    }

        */

So when I print $order_content, im getting 'order_id' null, how should I properly get id of order to fill its field in order_details? 因此,当我打印$ order_content时,我得到'order_id'null,我应该如何正确获取order的顺序来填充order_details中的字段?

In the end i should get something like this: 最后我应该得到这样的东西:

Orders:
1
1
+12345678
NY
processing
...

Order_details:
1
1
2
5
-----------
2
1
3
4
-----------
3
1
8
2
-----------

You need to save result to a variable: 您需要将结果保存到变量:

$order = (new Order)->create($data);

Or: 要么:

$order = Order::create($data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM