Laravel+PostgreSQL运行Seeder报错:operator does not exist: integer
PostgreSQL下Laravel Seeder更新sort_order报错修复
相关代码
迁移文件
Schema::create('posts', function($table) { $table->engine = 'InnoDB'; $table->increments('id')->unsigned(); $table->string('title'); $table->text('description')->nullable(); $table->integer('sort_order')->default(0); $table->boolean('status')->default(0); });
Seeder文件
class SeedPostsTable extends Seeder { public function run() { $posts = $this->getPosts(); foreach ($posts as $title => $column) { $posts[] = [ 'title' => $title, 'slug' => Str::slug($title), ]; } Post::insert($posts); Post::query()->update(['sort_order' => \DB::raw('`id`')]); } }
错误信息
SQLSTATE[42883]: Undefined function: 7 ERROR: operator does not exist: `integer` LINE 1: update "posts" set "sort_order" = `id` HINT: No operator matches the given name and argument type. You might need to add an explicit type cast. (SQL: update "posts" set "sort_order" = `id`)
问题背景
使用PostgreSQL作为数据库驱动,运行上述Seeder时触发错误,且需保持ID为integer类型,不能修改模型的$incrementing和$keyType属性。
修复方法
错误根源是PostgreSQL不支持MySQL的反引号`字段包裹语法,将DB::raw中的反引号移除或替换为PostgreSQL兼容的双引号即可:
方案1:移除反引号(推荐,字段名无特殊字符时)
修改Seeder中的更新语句:
Post::query()->update(['sort_order' => \DB::raw('id')]);
方案2:使用双引号(字段名含特殊字符时适用)
Post::query()->update(['sort_order' => \DB::raw('"id"')]);
执行修改后的Seeder即可正常完成数据填充与字段更新。
内容的提问来源于stack exchange,提问作者Andreas Hunter
相关产品推荐
相关产品推荐

