简体   繁体   中英

Mass Assignment Insert in Eloquent

In Laravel 5.1 I'm using mass assignment for inserts. But i want to learn how to bulk insert with Eloquent.

I need to insert sold products in order process.

Here is my data for insert.

   foreach($cart['fields'] as $key => $product)
    {
        $orderDetailData[] = [
            'order_id'       => $orderData['order_id'],
            'product_id'     => $product['id'],
            'quantity'       => $product['total_quantity'],
            'price'          => floatval($product['wholesale_price']),
            'vat'            => $product['vat'],
            'vat_value'      => floatval($product['vat_value']),
            'discount_ratio' => $product['discount_ratio'],
            'discount'       => floatval($product['discount_value']),
            'total_amount'   => floatval($product['total_amount']),
        ];
    }

Here is my code for insert

(new OrderDetail)->create($orderDetailData);

I think this method doesn't support bulk insert.

In Laravel 5.1 Manuel i see this.

DB::table('table')->insert($orderDetailData);

What should i do for mass assignment for bulk insert ? Should i use previous one (DB facade)

Because i'm getting error (500 internal server error) with this code

(new OrderDetail)->create($orderDetailData);

To insert/creae using mass-assignment you may declare an array in your Eloquent model like this one:

protected $fillable = [
    'order_id',
    'product_id',
    'quantity',
    'more fields names here...'
];

Defined field names will be inserted. Check the documentation for more. Also you may use forceCreate method which allows mass-assignment.

Also, the 500 internal server error is not obvious about the specific error so find it out.

this is example you can make array of your data and can insert the same way here going on.

$data = array(
    array(
        'name'=>'Coder 1', 'rep'=>'4096',
        'created_at'=>date('Y-m-d H:i:s'),
        'modified_at'=> date('Y-m-d H:i:s')
       ),
    array(
         'name'=>'Coder 2', 'rep'=>'2048',
         'created_at'=>date('Y-m-d H:i:s'),
         'modified_at'=> date('Y-m-d H:i:s')
       ),
    //...
);

YourModelName::create($data);

you can insert that way

$data = array(
array('name'=>'Coder 1', 'rep'=>'4096'),
array('name'=>'Coder 2', 'rep'=>'2048'),
//...
);
OrderDetail::insert($data);

also make fillable those fileds

protected $fillable = [
'name',
'rep_id',
];

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