如何在laravel中一次插入批量数据?

时间:2016-04-19 04:51:40

标签: php laravel bulk

大家好我试图一次在数据库中插入多行。目前我一次只能保存一行。 我做了以下事情:

public function addNewPriceRevision($data){
$PriceRevision=new ProductPriceRevision(
    [
        'product_id'=>$data->product_id,
        'invent_price'=>$data->invent_price,
        'revised_price'=>$data->revised_price,
        'effective_date'=>$data->effective_date,
        'deleted'=>$data->deleted,
        'remark'=>$data->remark,
        'user'=>$data->user,
        'date'=>$data->updated_at,

    ]
    );
 $PriceRevision->save();
 return Common::getJsonResponse(true, 'new price revision created successfully!', 200);
}

1 个答案:

答案 0 :(得分:0)

尝试将所有对象转换为数组,然后从多个数组创建一个数组:

$data = array($data1->toArray(), $data2->toArray());

如果您需要添加时间戳,则必须手动执行:

$date = date('Y-m-d H:i:s');

$data1 = $data1->toArray();
$data1['created_at'] = $date;
$data1['updated_at'] = $date;

$data2 = $data2->toArray();
$data2['created_at'] = $date;
$data2['updated_at'] = $date;

$data = array($data1, $data2);

然后您可以使用mass assignment功能创建行:

ProductPriceRevision::create($data);

并且不要忘记在$fillable模型中填充ProductPriceRevision数组:

protected $fillable = [
    'product_id',
    'invent_price',
    'revised_price',
    'effective_date',
    'deleted',
    'remark',
    'user',
    'updated_at'
];