【发布时间】:2014-12-27 06:06:31
【问题描述】:
迁移:
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)
protected $fillable = ['parent_location_id','location_id'];
当我这样做时:
$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, CONSTRAINTburbs_location_id_foreign外键 (location_id) 参考locations(id) 删除级联)SQL 插入到
burbs(parent_location_id,location_id,updated_at,created_at) 值 (12776, 321036, 2014-10-30 20:38:24, 2014-10-30 20:38:24)
第一个和第二个 ID 都存在于位置表中。
是的,parent_location_id 和 location_id 都是同一个位置表的键。
我也试过:FirstOrNew([]);和 FirstOrCreate([]);我什至尝试过
$burb->parent_location()->save($locationObj);
最后一个代码产生了“未知方法 save(),而在我的 Burb 模型中:
public function parent_location()
{
return $this->belongsTo('Location','parent_location_id');
}
.....我很茫然,我对laravel并不陌生,但我只花了3个小时调试这个。少了什么东西?快把我逼疯了!
【问题讨论】:
-
如果你这样做会发生什么
$burb->parent_location->save($locationObj); -
您确定这些 ID 存在于
locations表中吗? -
也许您正在使用另一个数据库,请确保
tb_prod数据库包含有效的密钥 -
乔纳森,我收到“未知方法保存()”错误。 Scopey,是的,我手动运行“SELECT WHERE”和 Razor,只有一个 DB。