我需要在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
$car->brand = 'Infinity';
。 - Wreigh$table->text('model');
也应该是一个字符串。模型是否会超过255个字符? - user320487composer.lock
文件中查看。 - Camilo