Laravel eloquent无法添加或更新子行:外键约束失败
嗨,这是我的亲戚: 地点:Laravel eloquent无法添加或更新子行:外键约束失败,laravel,laravel-5,eloquent,Laravel,Laravel 5,Eloquent,嗨,这是我的亲戚: 地点: public function _geoloc() { return $this->belongsTo('App\GeoLoc', 'id'); } Geoloc: public function locations() { return $this->hasOne('App\Location', 'geoloc_id'); } 控制器: $geoloc = new Geoloc; $geoloc->lat =
public function _geoloc()
{
return $this->belongsTo('App\GeoLoc', 'id');
}
Geoloc:
public function locations()
{
return $this->hasOne('App\Location', 'geoloc_id');
}
控制器:
$geoloc = new Geoloc;
$geoloc->lat = $request->input('lat');
$geoloc->lng = $request->input('lng');
$geoloc->save();
$geoloc_id = $geoloc->id;
$location = new Location;
$location->business_id = $business_id;
$location->latitude = $request->input('lat');
$location->longitude = $request->input('lng');
$location->slug = $request->input('name');
$location->geoloc_id = $geoloc_id;
$location->save();
完整错误消息:
SQLSTATE[23000]:完整性约束冲突:1452无法添加或
更新子行:外键约束失败
(liveoldham
locations
,CONSTRAINTlocations\u geoloc\u id\u foreign
外键(geoloc\u id
)引用删除级联上的geoloc
(id
)
更新级联时)(SQL:插入到位置(业务id
),
纬度
,经度
,slug
,地理位置id
,更新时间
,
在
处创建值(1,53.4867546,-2.0540665999942,实时和现在,
942017-06-27 15:22:512017-06-27 15:22:51)
所有的值都是正确的,行被插入到geoloc中,但它没有被插入到位置,这就是我得到的错误,如何修复
//编辑:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateLocationsTable extends Migration {
public function up()
{
Schema::create('locations', function(Blueprint $table) {
$table->increments('id');
$table->integer('business_id')->unsigned();
$table->float('latitude', 10,6);
$table->float('longitude', 10,6);
$table->integer('geoloc_id')->unsigned();
$table->string('slug', 29)->nullable();
$table->timestamps();
});
}
public function down()
{
Schema::drop('locations');
}
}
更新belongsTo关系时,应使用associate方法。
因此,与其
$location->geoloc_id = $geoloc_id;
使用
另外,请确保您的物品有正确的外键作为第二个参数
根据你的迁移情况
你的位置模型应该有
public function _geoloc()
{
return $this->belongsTo('App\GeoLoc', 'geoloc_id');
}
另外,我没有看到您使用迁移本身设置外键关系。因此,请将您的CreateLocationsTable
更新为:
$table->integer('geoloc_id')->unsigned();
$table->foreign('geoloc_id')->references('id')->on('_geoloc')->onDelete('cascade');
现在您应该重新运行迁移,它将正常工作。我现在得到:SQLSTATE[HY000]:一般错误:1364字段“geoloc\u id”没有默认值(SQL:insert-intolocations
(business\u id
,latitude
,longitude
,slug
,id
,updated\u at
,created\u at
)值(4,53.4867546,-2.0540665999942,Live&Now,972017-06-27 15:46:32)insert查询正在查找名为“id”而不是“geoloc_id”的字段。它应该是belongsTo('App\geoloc',geoloc_id');
。我必须查看您的表结构中的geoloc和locations。如果您发布这两个字段的迁移,效果会更好。我这样做了,但没有起作用。我得到了与问题中相同的错误
public function _geoloc()
{
return $this->belongsTo('App\GeoLoc', 'geoloc_id');
}
$table->integer('geoloc_id')->unsigned();
$table->foreign('geoloc_id')->references('id')->on('_geoloc')->onDelete('cascade');