문제

Eloquent Orm을 사용하여 Laravel에서 대량 데이터베이스 삽입을 어떻게 수행 할 수 있습니까?

Lavel 에서이 작업을 수행하고 싶습니다 : https://stackoverflow.com/a/10615821/600516/A> 그러나 나는 다음과 같은 오류가 발생합니다.

SQLSTATE [HY093] : 잘못된 매개 변수 x 호 : 명명 된 명명 된 및 위치 매개 변수가 혼합되었습니다.

도움이 되었습니까?

해결책

Eloquent::insert()를 사용할 수 있습니다.

예 :

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

Coder::insert($data);
.

다른 팁

우리는 TIMESTAMPS를 쉽게 업데이트하도록 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);
.

이 글을 읽는 사람은 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;
}
.

이것은 당신이 더 웅변 한 방식으로하는 방법입니다.

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

나는 그것에 대해 여러 번 검색, 마침내 아래와 같이 맞춤 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],
    ..................................
]);
.

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);
.

INSERT

를 수행하기 전에 전체 배열에 CREAGETE_AT 및 UPDATE_AT를 추가하는 것입니다.

카테고리 관계 삽입은 동일한 문제를 해결하고 eLoquent 모델에서 self ()를 사용하여 여러 저장 및 잡기 ID를 위대한 동일한 클래스의 인스턴스를 사용했습니다. $ obj= new self () "단일 레코드 만 저장합니다 ($ obj가 $ this이었습니다)

$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는 내 모델 이름입니다. 이것은 "false"를 성공적으로 삽입하면 "true"를 반환합니다.

어쩌면이 문제를 해결할 수있는 더 높은 획기적인 방법은 컬렉션을 사용하고 타임 스탬프를 이용하는 모델과 함께 삽입하는 것입니다.

<?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);
    }
}
.

해결 된 문제 ............. 마이그레이션을위한 ALTER 테이블 ...

$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();
        });
.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top