【问题标题】:Laravel 5 Mysql duplicate entry errorLaravel 5 Mysql重复输入错误
【发布时间】:2015-06-18 03:38:54
【问题描述】:

我正在使用 Laravel 5 向数据库中插入一些条目,但出现以下错误:

SQLSTATE[23000]:完整性约束违规:1062 键“category_id”的重复条目“1”(SQL:插入productsproduct_nameproduct_pricecategory_id)值(asdaszzz,123, 1))

据我了解,问题是我想在 category_id 表中添加的值已经存在于其他条目中,但问题是 category_id 表不是唯一键。下面我发布了迁移:

public function up()
{
    Schema::create('products', function($table)
    {
        $table->increments('id');
        $table->integer('category_id')->unsigned();
        $table->string('product_name', 255)->unique();
        $table->decimal('product_price', 10, 4);
        $table->dateTime('updated_at')->default(DB::raw('CURRENT_TIMESTAMP'));
    });

    Schema::table('products', function($table) {
        $table->foreign('category_id')->references('id')->on('categories');
    });
}

【问题讨论】:

    标签: mysql laravel-5


    【解决方案1】:

    为 category_id 添加 nullable

    $table->integer('category_id')->unsigned()->nullable();
    

    【讨论】:

    • 谢谢,似乎工作正常。为什么 nullable 可以解决问题?
    【解决方案2】:

    尝试添加表键...

    public function up()
    {
        Schema::create('products', function($table)
        {
            $table->increments('id');
            $table->integer('category_id')->unsigned();
            $table->string('product_name', 255)->unique();
            $table->decimal('product_price', 10, 4);
            $table->dateTime('updated_at')->default(DB::raw('CURRENT_TIMESTAMP'));
    
            $table->index('category_id');
    
            $table->foreign('category_id')->references('id')->on('categories');
        });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-10
      • 1970-01-01
      • 2015-06-26
      • 2019-10-17
      • 2013-05-05
      • 2021-08-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多