我有这个问题,我想删除多个表中的某些数据(不使用外键),所以我确实使查询和laravel抛出了SQL错误,其中包含我所做的查询。因此,我复制并粘贴了相同的查询,并在MySql中执行了它,并且可以正常工作。我不知道是什么问题。这是代码:
$deleteQuery = "DELETE FROM posts WHERE user_id= " . $user->user_id . ";";
$deleteQuery .= "DELETE FROM settings WHERE user_id= " . $user->user_id . ";";
$deleteQuery .= "DELETE FROM pictures WHERE user_id= " . $user->user_id . ";";
DB::delete($deleteQuery);
我也尝试过:
DB::delete($deleteQuery);
但这是行不通的。
我该怎么办?
答案 0 :(得分:1)
您要将多个delete语句放在一个位置。 DB::delete()
函数不支持该功能。
您可以像这样向数据库发送多个删除查询
DB::table("posts")->where("user_id", $userID)->delete();
DB::table("settings")->where("user_id", $userID)->delete();
DB::table("pictures")->where("user_id", $userID)->delete();
或者如果您真的想一口气做到这一点,则可以执行以下操作:
DB::RAW("DELETE FROM posts WHERE user_id= ?;
DELETE FROM settings WHERE user_id= ?;
DELETE FROM pictures WHERE user_id= ?,
array($userID, $userID, $userID));
看看查询生成器文档: https://laravel.com/docs/5.6/queries#deletes
答案 1 :(得分:0)
尝试一下
**DB::statement($deleteQuery);**
在Laravel中,DB::statement()
运行sql查询。
例如:
$ query =“ UPDATE
table_name
SETfield
=值”;
DB :: statement($ query);