我在使用 Laravel 5 删除数据时遇到了一些问题。我似乎陷入了“外键约束”,但我不明白为什么。
在我当前的数据库模型中,我有一个数据点表,它有一个指向传感器表的外键 (datapoints.sensors_id -> sensor.id)。
我正在尝试的代码:
Route::get('/truncateData', function() {
DB::table('datapoints')->truncate();
DB::table('sensors')->truncate();
return 'Done...';
});
结果:
SQLSTATE[42000]: Syntax error or access violation: 1701 Cannot truncate a table referenced in a foreign key constraint (
alerting
.datapoints
, CONSTRAINTdatapoints_sensor_id_foreign
FOREIGN KEY (sensor_id
) REFERENCESalerting
.sensors
(id
)) (SQL: truncatesensors
)
如果顺序相反(首先删除传感器),我会理解这个约束,但是当数据点为空时,删除传感器应该没有问题吗?我也试过:
DB::table('datapoints')->delete();
DB::table('sensors')->delete();
return 'Done...';
最后,我还尝试在删除语句之间显式添加“DB::commit()”,但都返回相同的结果。
这是正常行为吗?我错过了什么吗?
最佳答案
不,这是您的数据库的工作方式。您不能截断其他表引用的表。你可以做类似的事情
DB::statement('SET FOREIGN_KEY_CHECKS=0;');
DB::table('datapoints')->truncate();
DB::table('sensors')->truncate();
DB::statement('SET FOREIGN_KEY_CHECKS=1;');
要禁用外键检查,截断表并再次启用它。
关于php - Laravel Eloquent 截断 - 外键约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29119272/