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