简体   繁体   中英

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 ...

Order_details: id order_id prod_id amount ...

Controller:

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

    $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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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