在Laravel 5控制器中手动向数据库插入数据,无需表单。

4

我需要在Laravel 5控制器中手动向SQLite数据库插入一些数据,且不使用表单。

我尝试过以下方法:

第一种方法:

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

第二点:

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

第三方:

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

第一种方法可行,但我需要插入数千行数据,时间和性能并不好。

第二种和第三种方法会出现以下错误:

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

我不知道这个错误的含义,我已经查找了很多相关信息,尝试手动将数据填充到数据库中,但没有任何结果。
这是模型类:
namespace App;

use Illuminate\Database\Eloquent\Model;

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

这是迁移类:

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');
    }
}

编辑

我也进行了批量插入的测试:

第四个

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

DB::insert($arr);

...但是我遇到了一个新错误:

 ErrorException (E_NOTICE) Array to string conversion

在你的第三个方法中,为什么不直接访问“Model”的属性呢?例如:$car->brand = 'Infinity'; - Wreigh
1
我对你的第一种方法感到困惑。你用什么指标来衡量性能?这是一个直接插入,所以性能应该不是一个问题。 - user320487
顺便提一下,$table->text('model'); 也应该是一个字符串。模型是否会超过255个字符? - user320487
你是一次插入一条记录吗?DB:insert也接受数组进行批量插入,速度更快。 - user320487
你安装了哪个 Laravel 版本?你可以在 composer.lock 文件中查看。 - Camilo
显示剩余4条评论
3个回答

7

对于具有大量数据的数组(假设有10000行):

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

我将要插入的数据量分成了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);
    });
}

我之所以采用这种方式完成这项任务,是因为SQLite限制了同时插入条目的数量。使用这种解决方案的性能和速度非常高。 编辑 对于你们所有的收集爱好者:
collect($arr)->chunk(500)->each(function ($chunk) { 
    DB::transaction(function () use ($chunk) {
        DB::table('hotels')->insert($chunk->toArray());
    });
}). 

0
你的PHP版本是多少?我认为你写的代码应该可以工作。
试试这个。
$car = new Car;
$car->brand = 'Infinity';
$car->model = 'MS500';
$car->save();

=============================

编辑: 我在谷歌上搜索了一下,发现有人遇到了类似的问题。简单来说,这是 Laravel 安装的问题。 https://github.com/ollieread/multiauth/issues/29


那段代码产生了相同的错误。同时我已经执行了composer update,但使用所有这些方法都得到了相同的错误。我的PHP版本是PHP 7.0.25-0ubuntu0.16.04.1 - Yulio Aleman Jimenez
尝试删除整个供应商目录并从头重新安装所有内容。 - jesuisgenial
完成,相同的结果。我清除了composer缓存,但仍然没有改变! - Yulio Aleman Jimenez

0
$Car= new App\Car;
$options = $Car->options;
$options['brand'] = 'value';
$options['model'] = 'value';
$Car->options = $options;
$Car->save();

它必须工作


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接