简体   繁体   中英

Set a fixed value for a field in a multi-row insert in Laravel

I have an array $cart :

$cart = [
    ["product_id" => 1, "price" => 20, "amount" => 5, "tax" => 15],
    ["product_id" => 2, "price" => 30, "amount" => 10, "tax" => 20],
    ...
];

I can do

DB::table('order_products')->insert($cart);

But I need to insert this array into a table that has the same columns + order_id . The order_id will be the same for all rows, it's the insert id of the previous query. Is it possible to set a fixed value for order_id for all rows?

When you use eloquent models and your Order model has a hasMany relation order_products() , then you can use the createMany() method on the relation:

$order->order_products()->createMany($cart);

For save() and saveMany() methods as well as for create() and createMany() , if called on a relation, the foreign key (in your case order_id ) will be set automatically taken from the parent $order entity.

In the documentation you will also find this note:

Before using the create method, be sure to review the documentation on attribute mass assignment .

Most important is the $fillable property, which you already figured out.

Note that you should also be able to use create() for the order itself. I don't know why it didn't work for you. Check the $fillable property in the Order model. Also usually an order belongs to a user - so you would need to assign user_id , which might be missing in the array. What could work is

$order = Auth:user()->orders()->create($orderArray);

The user_id would be taken from Auth:user() and assigned to the order automatically.

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