Yul*_*nez 2 php sqlite laravel
我需要将一些数据插入到 sqlite 数据库中,在(Laravel 5)控制器中手动插入并且没有表单。
我试过这种方法:
第一:
DB::insert('insert into cars values (?, ?, ?)', [1, "Infinity", "MS500"]);
Run Code Online (Sandbox Code Playgroud)
第二:
Car::create([
'brand' => 'Infinity',
'model' => 'MS500',
]);
Run Code Online (Sandbox Code Playgroud)
第三:
$car = new Car();
$car->setAttribute('brand', 'Infinity');
$car->setAttribute('model', 'MS500');
$car->save();
Run Code Online (Sandbox Code Playgroud)
在第一个方法的作品,但我需要插入的行万,时间和性能也不是那么好。
在第2和第3的方法给我这个错误:
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
Run Code Online (Sandbox Code Playgroud)
我不知道这个错误是什么意思,我已经找到了很多关于它的信息,并且即将手动将数据填充到数据库中,没有结果。
这是模型类:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Car extends Model
{
const CREATED_AT = null;
const UPDATED_AT = null;
protected $fillable = ['brand', 'model'];
}
Run Code Online (Sandbox Code Playgroud)
这是迁移类:
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');
}
}
Run Code Online (Sandbox Code Playgroud)
我也测试了批量插入:
第四名
$arr = [
[
'brand' => 'Infinity',
'model' => 'MS500',
],
[
'brand' => 'Toyota',
'model' => 'LK2500',
],
];
DB::insert($arr);
Run Code Online (Sandbox Code Playgroud)
...但我收到了这个新错误:
ErrorException (E_NOTICE) Array to string conversion
Run Code Online (Sandbox Code Playgroud)
对于包含数据的大量数组(假设为 10000 行):
$arr = [
[
'brand' => 'Infinity',
'model' => 'MS500',
],
[
'brand' => 'Toyota',
'model' => 'LK2500',
],
...
// 10000 rows
];
Run Code Online (Sandbox Code Playgroud)
我将要插入的数据量分成 500 个块,然后插入到事务内部的数据库中。
$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);
});
}
Run Code Online (Sandbox Code Playgroud)
我以这种方式完成了这项任务,因为 SQLite 同时限制了插入的数量。此解决方案的性能和速度非常高。
编辑
对于所有收藏爱好者:
collect($arr)->chunk(500)->each(function ($chunk) {
DB::transaction(function () use ($chunk) {
DB::table('hotels')->insert($chunk->toArray());
});
}).
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10743 次 |
| 最近记录: |