Php laravel save()用“阻塞”;完整性约束冲突";-所有钥匙都设置正确
迁移:Php laravel save()用“阻塞”;完整性约束冲突";-所有钥匙都设置正确,php,laravel,eloquent,Php,Laravel,Eloquent,迁移: Schema::create('burbs', function($table) { $table->engine = 'InnoDB'; $table->increments('id'); $table->integer('parent_location_id')->nullable()->index()->unsigned(); $table->integer('loc
Schema::create('burbs', function($table)
{
$table->engine = 'InnoDB';
$table->increments('id');
$table->integer('parent_location_id')->nullable()->index()->unsigned();
$table->integer('location_id')->nullable()->index()->unsigned();
$table->timestamps();
$table->foreign('parent_location_id')->references('id')->on('locations')->onDelete('cascade');
$table->foreign('location_id')->references('id')->on('locations')->onDelete('cascade');
});
模型(Burb)
当我这样做时:
$burb = Burb::where(['location_id' => $location_id])->first();
if(!$burb) $burb = new Burb;
$burb->parent_location_id = $parent_id;
$burb->location_id = $location_id;
$burb->save();
得到这个:
完整性约束冲突:1452无法添加或更新子项
行:外键约束失败(tb_prod
burbs
,约束
burbs\u location\u id\u foreign
外键(location\u id
)引用
位置
(id
)在删除级联上)
SQL插入到burbs
(parent\u location\u id
,location\u id
,
在
处更新,在
处创建)值(127763210362014-10-30
20:38:242014-10-30 20:38:24)
第一个和第二个ID都存在于位置表中
是的,父位置id和位置id都是同一位置表的键
我也试过:FirstOrNew([]);和FirstOrCreate([]);我甚至试过
$burb->parent_location()->save($locationObj);
最后一段代码生成了“unknown method save(),而在我的Burb模型中:
public function parent_location()
{
return $this->belongsTo('Location','parent_location_id');
}
…我不知所措,我对laravel并不陌生,但我只是花了3个小时调试这个。缺少什么?它让我发疯了!迁移时的->index()
和->nullable()
真的有必要吗?它们是外键,所以,…但这取决于你:D
尝试将迁移更改为:
Schema::create('burbs', function($table)
{
$table->engine = 'InnoDB';
$table->increments('id');
$table->integer('parent_location_id')->unsigned();
$table->integer('location_id')->unsigned();
$table->timestamps();
$table->foreign('parent_location_id')->references('id')->on('locations')->onDelete('cascade');
$table->foreign('location_id')->references('id')->on('locations')->onDelete('cascade');
});
因为上次我也有同样的问题,但我忘了把
->无符号()
我觉得自己非常愚蠢。第二个id(location_id)是Insert上错误表中的错误id。当我手动运行几个测试用例(在mysql中)时,我很幸运这些id存在,但对于大多数实时数据来说都失败了
谢谢你的帮助。有点相关的一点:忘记->unsigned()以前让我很难过。如果你做
$burb->parent\u location->save($locationObj),会发生什么
您确定这些ID存在于位置表中吗?可能您正在使用另一个数据库,请确保tb_prod
数据库包含有效的密钥Jonathan,我收到“unknown method save()”错误。Scopey,是的,我运行了手动“选择位置”和Razor,只有一个DB。
Schema::create('burbs', function($table)
{
$table->engine = 'InnoDB';
$table->increments('id');
$table->integer('parent_location_id')->unsigned();
$table->integer('location_id')->unsigned();
$table->timestamps();
$table->foreign('parent_location_id')->references('id')->on('locations')->onDelete('cascade');
$table->foreign('location_id')->references('id')->on('locations')->onDelete('cascade');
});