Laravel Eloquent truncate - 外键约束
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29119272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel Eloquent truncate - Foreign key constraint
提问by Wesley
I am having some issues with deleting data using Laravel 5. I seem to be stuck on a 'foreign key constraint', while I don't see why.
我在使用 Laravel 5 删除数据时遇到了一些问题。我似乎被困在“外键约束”上,但我不明白为什么。
In my current database model I have a datapoints table, which has a foreign key to the sensors table (datapoints.sensors_id -> sensor.id).
在我当前的数据库模型中,我有一个数据点表,它有一个传感器表的外键(datapoints.sensors_id -> sensor.id)。
The code I am trying:
我正在尝试的代码:
Route::get('/truncateData', function() {
DB::table('datapoints')->truncate();
DB::table('sensors')->truncate();
return 'Done...';
});
});
The result:
结果:
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
)
SQLSTATE[42000]:语法错误或访问冲突:1701 无法截断外键约束 (
alerting
.datapoints
, CONSTRAINTdatapoints_sensor_id_foreign
FOREIGN KEY (sensor_id
) REFERENCESalerting
.sensors
(id
))中引用的表(SQL: truncatesensors
)
I would understand this constraint if the order would be inverse (first deleting sensors), but when datapoints is empty, there should be no problem deleting sensors? I have also tried:
如果顺序相反(首先删除传感器),我会理解这个约束,但是当数据点为空时,删除传感器应该没有问题?我也试过:
DB::table('datapoints')->delete();
DB::table('sensors')->delete();
return 'Done...';
Lastly I also tried adding explicitly 'DB::commit()' between the delete statements, but all return the same result.
最后,我还尝试在删除语句之间显式添加 'DB::commit()',但都返回相同的结果。
Is this normal behaviour? Am I missing something?
这是正常行为吗?我错过了什么吗?
Thanks in advance.
提前致谢。
Cheers,
干杯,
Wesley
卫斯理
回答by Maksym Cierzniak
No, this is the way your database works. You can't truncate table that is referenced by some other table. You may do something like
不,这是您的数据库的工作方式。您不能截断其他表引用的表。你可以做类似的事情
DB::statement('SET FOREIGN_KEY_CHECKS=0;');
DB::table('datapoints')->truncate();
DB::table('sensors')->truncate();
DB::statement('SET FOREIGN_KEY_CHECKS=1;');
to disable foreign key checks, truncate tables and enable it again.
禁用外键检查,截断表并再次启用它。
回答by JoeGalind
If you prefer to use Eloquent objects, Maksym's answer the "Eloquent" way
如果您更喜欢使用 Eloquent 对象,Maksym 的回答是“Eloquent”方式
use Illuminate\Support\Facades\Schema;
use App\Models\Datapoint;
use App\Models\Sensor;
Schema::disableForeignKeyConstraints();
Datapoint::truncate();
Sensor::truncate();
Schema::enableForeignKeyConstraints();