使用雄辩的ORM在Laravel中批量插入

php database laravel eloquent

143053 观看

10回复

2019 作者的声誉

我们如何使用Eloquent ORM在Laravel中执行批量数据库插入?

我想在Laravel中完成此任务:https://stackoverflow.com/a/10615821/600516 但我收到以下错误。

SQLSTATE [HY093]:参数号无效:混合命名和位置参数。

作者: phoenixwizard 的来源 发布者: 2012 年 10 月 3 日

回应 (10)


249

3835 作者的声誉

决定

你可以使用Eloquent::insert()

例如:

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

Coder::insert($data);
作者: GTF 发布者: 27.11.2012 11:54

62

864 作者的声誉

我们可以更新GTF答案以轻松更新时间戳

$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')
       ),
    //...
);

Coder::insert($data);

更新:为了简化我们可以使用碳的日期,@ Pedro Moreira建议

$now = Carbon::now('utc')->toDateTimeString();
$data = array(
    array(
        'name'=>'Coder 1', 'rep'=>'4096',
        'created_at'=> $now,
        'modified_at'=> $now
       ),
    array(
         'name'=>'Coder 2', 'rep'=>'2048',
         'created_at'=> $now,
         'modified_at'=> $now
       ),
    //...
);

Coder::insert($data);

UPDATE2:对于laravel 5,使用updated_at而不是modified_at

$now = Carbon::now('utc')->toDateTimeString();
$data = array(
    array(
        'name'=>'Coder 1', 'rep'=>'4096',
        'created_at'=> $now,
        'updated_at'=> $now
       ),
    array(
         'name'=>'Coder 2', 'rep'=>'2048',
         'created_at'=> $now,
         'updated_at'=> $now
       ),
    //...
);

Coder::insert($data);
作者: Eslam Salem Mahmoud 发布者: 26.10.2014 05:01

-1

5358 作者的声誉

$start_date = date('Y-m-d h:m:s');        
        $end_date = date('Y-m-d h:m:s', strtotime($start_date . "+".$userSubscription['duration']." months") );
        $user_subscription_array = array(
          array(
            'user_id' => $request->input('user_id'),
            'user_subscription_plan_id' => $request->input('subscription_plan_id'),
            'name' => $userSubscription['name'],
            'description' => $userSubscription['description'],
            'duration' => $userSubscription['duration'],
            'start_datetime' => $start_date,
            'end_datetime' => $end_date,
            'amount' => $userSubscription['amount'],
            'invoice_id' => '',
            'transection_datetime' => '',
            'created_by' => '1',
            'status_id' => '1', ),
array(
            'user_id' => $request->input('user_id'),
            'user_subscription_plan_id' => $request->input('subscription_plan_id'),
            'name' => $userSubscription['name'],
            'description' => $userSubscription['description'],
            'duration' => $userSubscription['duration'],
            'start_datetime' => $start_date,
            'end_datetime' => $end_date,
            'amount' => $userSubscription['amount'],
            'invoice_id' => '',
            'transection_datetime' => '',
            'created_by' => '1',
            'status_id' => '1', )
        );
        dd(UserSubscription::insert($user_subscription_array));

UserSubscription是我的型号名称。如果成功插入,则返回“true”,否则返回“false”。

作者: Nikunj K. 发布者: 27.08.2016 09:32

23

1401 作者的声誉

对于正在阅读本文的人,请查看createMany()方法

/**
 * Create a Collection of new instances of the related model.
 *
 * @param  array  $records
 * @return \Illuminate\Database\Eloquent\Collection
 */
public function createMany(array $records)
{
    $instances = $this->related->newCollection();

    foreach ($records as $record) {
        $instances->push($this->create($record));
    }

    return $instances;
}
作者: Alex 发布者: 25.01.2017 07:18

13

4964 作者的声誉

这是你如何以更有说服力的方式做到这一点,

    $allintests = [];
    foreach($intersts as $item){ //$intersts array contains input data
        $intestcat = new User_Category();
        $intestcat->memberid = $item->memberid;
        $intestcat->catid= $item->catid;
        $allintests[] = $intestcat->attributesToArray();
    }
    User_Category::insert($allintests);
作者: imal hasaranga perera 发布者: 04.06.2017 12:12

-1

359 作者的声誉

也许更多的Laravel解决这个问题的方法是使用一个集合并使用模型利用时间戳循环插入。

<?php

use App\Continent;
use Illuminate\Database\Seeder;

class InitialSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        collect([
            ['name' => 'América'],
            ['name' => 'África'],
            ['name' => 'Europa'],
            ['name' => 'Asia'],
            ['name' => 'Oceanía'],
        ])->each(function ($item, $key) {
            Continent::forceCreate($item);
        });
    }
}

编辑:

对不起我的误会。对于批量插入,这可能有所帮助,也许有了这个,你可以制作好的播种机并对它们进行一些优化。

<?php

use App\Continent;
use Carbon\Carbon;
use Illuminate\Database\Seeder;

class InitialSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $timestamp = Carbon::now();
        $password = bcrypt('secret');

        $continents = [
            [
                'name' => 'América'
                'password' => $password,
                'created_at' => $timestamp,
                'updated_at' => $timestamp,
            ],
            [
                'name' => 'África'
                'password' => $password,
                'created_at' => $timestamp,
                'updated_at' => $timestamp,
            ],
            [
                'name' => 'Europa'
                'password' => $password,
                'created_at' => $timestamp,
                'updated_at' => $timestamp,
            ],
            [
                'name' => 'Asia'
                'password' => $password,
                'created_at' => $timestamp,
                'updated_at' => $timestamp,
            ],
            [
                'name' => 'Oceanía'
                'password' => $password,
                'created_at' => $timestamp,
                'updated_at' => $timestamp,
            ],
        ];

        Continent::insert($continents);
    }
}
作者: Francisco Daniel 发布者: 21.09.2017 11:28

3

1328 作者的声誉

我多次搜索它,最后使用timestamps如下定制:

$now = Carbon::now()->toDateTimeString();
Model::insert([
    ['name'=>'Foo', 'created_at'=>$now, 'updated_at'=>$now],
    ['name'=>'Bar', 'created_at'=>$now, 'updated_at'=>$now],
    ['name'=>'Baz', 'created_at'=>$now, 'updated_at'=>$now],
    ..................................
]);
作者: srmilon 发布者: 23.12.2017 07:28

1

8567 作者的声誉

Eloquent::insert 是正确的解决方案,但它不会更新时间戳,所以你可以做类似下面的事情

 $json_array=array_map(function ($a) { 
                        return array_merge($a,['created_at'=> 
                                            Carbon::now(),'updated_at'=> Carbon::now()]
                                           ); 
                                     }, $json_array); 
 Model::insert($json_array);

我们的想法是在插入之前在整个数组上添加created_at和updated_at

作者: sumit 发布者: 16.02.2019 03:16

-3

1 作者的声誉

已解决的问题.......更换移民表...

$table->timestamp('created_at')->nullable()->useCurrent();

简单

Schema::create('spider_news', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('source')->nullable();
            $table->string('title')->nullable();
            $table->string('description')->nullable();
            $table->string('daterss')->nullable();

            $table->timestamp('created_at')->nullable()->useCurrent();
            $table->timestamp('update_at')->nullable()->useCurrent();
        });
作者: Alexandre Possebon 发布者: 14.06.2019 05:43

0

2086 作者的声誉

对于类别关系插入,我遇到了同样的问题并且不知道,除了在我雄辩的模型中我使用Self()在foreach中有一个相同类的实例来记录多个保存和抓取id。

foreach($arCategories as $v)
{                
    if($v>0){
        $obj = new Self(); // this is to have new instance of own
        $obj->page_id = $page_id;
        $obj->category_id = $v;
        $obj->save();
    }
}

没有“$ obj = new Self()”它只保存单个记录(当$ obj为$ this时)

作者: justnajm 发布者: 16.06.2019 09:00
32x32