简体   繁体   English

雄辩的批量分配插入

[英]Mass Assignment Insert in Eloquent

In Laravel 5.1 I'm using mass assignment for inserts. 在Laravel 5.1中,我使用插入的质量分配。 But i want to learn how to bulk insert with Eloquent. 但是我想学习如何用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. 在Laravel 5.1 Manuel中,我看到了这一点。

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 因为此代码出现错误(500个内部服务器错误)

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

To insert/creae using mass-assignment you may declare an array in your Eloquent model like this one: 要使用质量分配进行插入/创建,可以在Eloquent模型中声明一个数组,如下所示:

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. 同样,您可以使用forceCreate方法,该方法允许进行批量分配。

Also, the 500 internal server error is not obvious about the specific error so find it out. 此外, 500 internal server error对于特定错误并不明显,因此请找出来。

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',
];

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

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