简体   繁体   中英

Foreign key issue while inserting data in child table Laravel

I am trying to insert data in orders table and then save order details in order_details table. Following is the code that I'm trying

$order = Order::create($request->all());
$order->order_detail()->insert($request->order_detail); //$request->order_detail is an array

In my model I have provided relationships

Order Model

public function order_detail(){
   return $this->hasMany(OrderDetail::class, 'order_id');
}

Order Detail Model

public function order(){
   return $this->belongsTo(Order::class,'order_id');
}

but it returns me General error: 1364 Field 'order_id' doesn't have a default value as order_id is a foreign key in order_details table

How can I do it without giving order_id manually

Since your $request->order_detail isn't gonna contain order_id. You can take that from the newly created $order.

$order = Order::create($request->all()); // upon create, you can access the order_id by doing $order->id

$orderDetails = [];

foreach($request->order_detail as $details) {
    $orderDetails[] = [
        array_merge($details, ['order_id' => $order->id]);
    ];
}

$order->order_detail()->insert($orderDetails);

I am going to assume that $request->order_detail is an array of many order_details .

The problem with insert is that you are not using Eloquent but the query builder, therefore Laravel is not able to fill the order_id by itself, if you use createMany instead it will be able to do so:

$order = Order::create($request->all());
$order->order_detail()->createMany($request->order_detail);

From the docs :

You may use the createMany method to create multiple related models:

$post = App\Post::find(1);

$post->comments()->createMany([
    [
        'message' => 'A new comment.',
    ],
    [
        'message' => 'Another new comment.',
    ],
]);

Sounds like a database issue. The column order_id has AUTO_INCREMENT, meaning it would generate a number upon insert.

Try inserting with phpMyAdmin to see whether AUTO_INCREMENT works. Or use SHOW TABLE STATUS and check AUTO_INCREMENT.

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