因为测试没有测试数据库,所以我使用手动生成的sql脚本来清理我的生产数据库的一个数据库克隆。假设我的遗留数据库如下:
ohimesama
id: PK
namae: Varchar (200)
oujisama:
id: pk
namae: Varchar(200)
ohimesamagasuki:
id: pk
ohimesama_id: fk ohimesama
oujisama_id: fk oujisama测试数据库清理sql (cleanup.sql)脚本是:
DELETE * from ohimesama where namae not in ['Gardinelia', 'Jasmine'];
DELETE * from oujisama where namae not in ['Gaouron', 'Sasuke','Aladin'];
DELETE * from ohimesamagasuki where ohimesama_id not in (SELECT id from ohimesama) and oujisma not in
(SELECT id from oujisama); 因为我希望能够用一个事务执行所有这些命令,所以我希望能够读取cleanup.sql文件,并使用Laravel数据库层执行sql命令,而不需要手动编写它。
我怎么能做到这一点?
发布于 2019-11-13 22:59:58
正如在这个medium article中所看到的,您可以使用这一个单独的线条:
DB::unprepared(file_get_contents('cleanup.sql'));唯一的问题是sql命令没有分块,因此在大型sql文件中可能会导致速度减慢。此外,file_get_contents也有读取限制。
对于大型sql文件,建议手动读取并将其分块到selerate sql命令中。
此外,如果一个命令执行失败,则不会像在shell环境中通过mysql或psql命令那样继续执行下一个命令
https://stackoverflow.com/questions/58839871
复制相似问题