php Laravel SQLSTATE[42883]:未定义的函数:7错误:操作员不存在:整数

o3imoua4  于 2023-03-21  发布在  PHP
关注(0)|答案(2)|浏览(236)

我喜欢这个迁移文件:

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

我也有种子:

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

作为数据库驱动程序,我使用Postgres,当我运行这个seeder时,得到这样的错误:

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`)

我不能在我的模型中设置public $incrementing = false;protected $keyType = 'string';,因为我需要整数数据类型作为ID列。
如何修复此错误?

dldeef67

dldeef671#

我猜问题出在数据类型的不匹配上:
在Laravel中,$table->increments('id')是一个大的无符号整数,而不是整数。将sort_order设置为相同的类型:

Schema::create('posts', function($table)
{
    $table->engine = 'InnoDB';
    $table->increments('id')->unsigned();
    $table->string('title');
    $table->text('description')->nullable();
    $table->unsignedBigInteger('sort_order')->default(0);
    $table->boolean('status')->default(0);
});
8ulbf1ek

8ulbf1ek2#

Post::query()->update(['sort_order' => \DB::raw('`id`')]);

您应该用途:

Post::query()->update(['sort_order' => \DB::raw('"id"')]);

相关问题