我正在创建一个laravel应用程序,允许用户发表博客文章。
Post模型如下所示:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    // Table Name
    protected $table = 'posts';
    // Primary key
    public $primaryKey = 'id';
    // Timestamps
    public $timestamps = true;
}

这是迁移文件:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->mediumText('body');
            $table->timestamps();
        });
    }

    /**
    * Reverse the migrations.
    *
    * @return void
    */
    public function down()
    {
       Schema::dropIfExists('posts');
    }
}

我正在使用PostgreSQL数据库,问题是$table->increments('id');使ID列成为“Integer”类型,而不是Postgres中用于此类型字段的“Serial”。
当我尝试更新帖子时,这将创建以下错误:
Unique violation: 7 ERROR: duplicate key value violates unique constraint "posts_pkey" DETAIL: Key (id)=(1) already exists. (SQL: insert into "posts" ("title", "body", "updated_at", "created_at") values (Post 3, Test test test, 2019-03-06 17:27:37, 2019-03-06 17:27:37) returning "id")
我需要一种方法来定义这个字段为“serial”。
编辑:
我的PostsController存储函数如下所示:
public function store(Request $request)
{
    $this->validate($request, [
        'title' => 'required',
        'body' => 'required'
    ]);

    // Create post
    $post = new Post;
    $post->title = $request->input('title');
    $post->body = $request->input('body');
    $post->save();

    return redirect('/posts')->with('success', 'Post created');
}

最佳答案

默认情况下,'id'列是主键,您不需要在模型中指定它,也许这就是它试图使列成为整数的原因。
尝试删除

public $primaryKey = 'id';

从模型定义中尝试执行新的迁移并运行查询。
我不确定这个答案,但它有点长的评论,所以张贴一个答案

关于php - PostgreSQL中的ID列(Laravel 5.8),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55029544/

10-13 00:47
查看更多