【发布时间】:2015-05-21 07:02:03
【问题描述】:
1452 Cannot add or update a child row: a foreign key constraint fails (`bpr`.`trips`, CONSTRAINT `trips_driver_user_id_foreign` FOREIGN KEY (`driver_user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE)
是错误。
通过 MySQL 手动添加一行可以正常工作。如果我通过我的应用程序来做 - 不。
我试图插入的id 是正确的(它存在并且是一个整数)。我检查了外键和东西,一切看起来都很好。不知道是什么问题...
一些代码:
$input = Input::all();
Trip::create([
'route_from' => $input['route_from'],
'route_to' => $input['route_to'],
... adding other stuff ...
'driver_user_id' => Auth::user()->id
]);
当我var_dump(Auth::user()->id) 时,我确实得到了正确的int 号码,这是某个用户正确对应的ID。
在 Trip 模型中:
protected $hidden = [
'id'
];
protected $fillable = [
'route_from',
'route_to',
...
'driver_user_id'
];
public function Trip()
{
return $this->belongsTo('User', 'driver_user_id', 'id');
}
在用户模型中:
public function Trips()
{
return $this->hasMany('Trip');
}
【问题讨论】:
-
我们能看到代码吗?或者你正在使用什么框架等等,只是更多的信息
-
@IkoTikashi - 完成。 :)
-
看这里,希望对你有帮助:stackoverflow.com/questions/20705539/…
-
@IkoTikashi - 这对我没有帮助。在尝试插入旅行行并将其链接到用户之前,我已经在数据库中创建了特定用户的行。否则我将无法从
Auth::获得它的id。 -
对不起,应该更彻底地阅读。在这里我帮不了你,对不起:(
标签: php mysql laravel laravel-4