是什么阻止我添加具有外键值的行


What prevents me from adding a row with foreign key value?

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。

在行程模型中:

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');
}

我有一种直觉,这些属性是被保护的。您的代码似乎正确,但是您收到的错误源自数据库。你能像这样尝试一下,看看它是否有效:

$trip = new Trip;
$trip->unguard();
$trip->fill([
            'route_from'       => $input['route_from'],
            'route_to'         => $input['route_to'],
            ... adding other stuff ...
            'driver_user_id'   => Auth::user()->id
        ]);
$trip->save();

在模型上使用 create 方法使得调试正在发生的事情变得困难。