duandun3178 2018-02-02 02:35
浏览 61
已采纳

在没有表单的laravel 5控制器内手动将数据插入数据库

I need to insert some data into a sqlite database, manually inside a (Laravel 5) controller and without a form.

I've tried with this methods:

1st:

DB::insert('insert into cars values (?, ?, ?)', [1, "Infinity", "MS500"]);

2nd:

Car::create([
    'brand' => 'Infinity',
    'model' => 'MS500',
]);

3rd:

$car = new Car();
$car->setAttribute('brand', 'Infinity');
$car->setAttribute('model', 'MS500');
$car->save();

The 1st method works, but I need to insert thousand of rows, and the time and performance is not so good.

The 2nd and 3rd methods give me this error:

Missing argument 2 for Illuminate\Database\Eloquent\Model::setAttribute(), called in /var/www/html/AppLaravel/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php on line 525 and defined

I don't know what means this error, I have found a lot about it, and about to populate the data into the database manually, with no results.

This is the model class:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Car extends Model
{
    const CREATED_AT = null;
    const UPDATED_AT = null;
    protected $fillable = ['brand', 'model'];
}

This is the migration class:

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateCarsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('cars', function (Blueprint $table) {
            $table->increments('id');
            $table->string('brand');
            $table->text('model');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('cars');
    }
}

EDIT

I've tested with the bulk insertion too:

4th

$arr = [
    [
        'brand' => 'Infinity',
        'model' => 'MS500',
    ],
    [
        'brand' => 'Toyota',
        'model' => 'LK2500',
    ],
];

DB::insert($arr);

... but I got this new error:

 ErrorException (E_NOTICE) Array to string conversion
  • 写回答

3条回答 默认 最新

  • doutao5499 2018-02-02 05:59
    关注

    For an extensive array of arrays with the data (let's say 10000 rows):

    $arr = [
        [
            'brand' => 'Infinity',
            'model' => 'MS500',
        ],
        [
            'brand' => 'Toyota',
            'model' => 'LK2500',
        ],
        ...
        // 10000 rows
    ];
    

    I separated the amount of data to insert in chunks of 500, and I inserted into the database inside of transactions.

    $div = 500;
    
    for ($i = 0; $i < intdiv(count($arr), $div); $i++) {
    
        $new_arr = [];
    
        for ($j = ($i * $div); $j < (($i + 1) * $div); $j++) {
            $new_arr[] = $arr[$j];
        }
    
        DB::transaction(function () use ($new_arr) {
            DB::table('hotels')->insert($new_arr);
        });
    }
    

    I've done this task of this way because SQLite restrict the amount of insertions at the same time. the performance and the speed with this solution is very high.

    Edit

    For all you collection fans:

    collect($arr)->chunk(500)->each(function ($chunk) { 
        DB::transaction(function () use ($chunk) {
            DB::table('hotels')->insert($chunk->toArray());
        });
    }). 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分