Laravel 5.2 - 完整性约束违规:1452无法添加或更新子行:外键约束失败

时间:2016-06-24 17:30:50

标签: php mysql laravel laravel-5.2

这个问题有already been asked many times,我经历了所有的答案,但都没有解决我得到的错误。

我使用的是Laravel 5.2

我有2张桌子 - 分类和类别。当我想创建一个分类时,我收到错误消息:

  

SQLSTATE [23000]:完整性约束违规:1452无法添加或更新子行:外键约束失败(myclassifiedclassifieds,CONSTRAINT classifieds_category_id_foreign FOREIGN KEY({{ 1}})参考category_idcategories))

这样定义的迁移文件:

表示id表:

classifieds

表示public function up() { Schema::create('classifieds', function (Blueprint $table) { $table->increments('id'); $table->string('title'); $table->string('description'); $table->string('price'); $table->timestamps(); }); } public function down() { Schema::drop('classifieds'); } 表:

categories

并添加外键

public function up()
{
    Schema::create('categories', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->timestamps();
    });
}

public function down()
{
    Schema::drop('categories');
}

模型是:

public function up() { Schema::table('classifieds', function(Blueprint $table) { $table->integer('category_id')->unsigned(); $table->foreign('category_id')->references('id')->on('categories'); }); } public function down() { Schema::table('classifieds', function(Blueprint $table) { $table->dropForeign('classifieds_category_id_foreign'); }); } 型号:

Classified

class Classified extends Model { protected $table = 'classifieds'; protected $fillable = ['title', 'category_id', 'description', 'price']; protected $hidden = []; public function category(){ return $this->belongsTo('App\Category'); } } 型号:

Category

并且控制器中的store方法定义如下:

class Category extends Model
{
   protected $table = 'categories';
   protected $fillable = ['name'];

   protected $hidden = [];

   public function classifieds(){
       return $this->hasMany('App\Classified');
   }
}

我在数据库设置中的错误是什么?

1 个答案:

答案 0 :(得分:0)

当您尝试保存Classified并为Category表中指定了尚不存在的类别ID的外键时,会发生这种情况。

如果您还没有外国身份证,请将其保留为空,并确保在迁移时执行此操作以允许空值;

 public function up()
{
    Schema::table('classifieds', function(Blueprint $table) {
        $table->integer('category_id')->unsigned();
        $table->foreign('category_id')->references('id')->on('categories')->onDelete('set null');
    });
}

public function down()
{
    Schema::table('classifieds', function(Blueprint $table) {
        $table->dropForeign('classifieds_category_id_foreign');
    });
}