php - PostgreSQL (Laravel 5.8) 中的 ID 列

标签 php laravel postgresql database-migration

我正在创建一个允许用户发表博文的 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。

当我尝试更新帖子时,这会产生以下错误: 唯一违规:7 错误:重复键值违反唯一约束“posts_pkey”详细信息:键 (id)=(1) 已存在。 (SQL: insert into "posts"("title", "body", "updated_at", "created_at") 值 (Post 3, Test test test, 2019-03-06 17:27:37, 2019-03-06 17:27:37) 返回“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 (Laravel 5.8) 中的 ID 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55029544/

相关文章:

php - 如何在 laravel 中使用 maatwebsite 设计 excel 表格

php - Laravel Eloquent setAppends() 到整个模型集合?

postgresql - clojure:如何将 jdbc4array 转换为 clojure 的 seq?

sql - 寻求有关此 table 上足球游戏数据库设计的帮助/验证

php - 意外的括号-PHP

php - mysql_affected_rows 不显示消息

javascript - 将 X-editable 与 CodeIgniter 3 CSRF 问题结合使用

php - 在 php 中使用 mysql_real_escape_string() 时出现连接错误

php - 拉拉维尔 : how to avoid time overlapping?

mysql - 按 ID 分组并在 SQL 中查找最小和最大时间