将单行放入变量并通过一个查询同时删除它

put single row to variable and delete it at same time with one query

我在 mysql 数据库中有一个 password_resets table,我想获取单个原始数据并在 Lumen 中使用 DB 外观的一个查询将其删除这个:

$reset_row = DB::table('password_resets')->where('token', $request->token)->first()->delete();

但是我有一个错误:

Call to undefined method stdClass::delete()

我试试这个代码:

  $reset_row = DB::table('password_resets')->where('token', $request->token)
  //do my work whith $reset_row->first();
  $reset_row->delete();

但我认为这种方式使用 2 个查询来完成这项工作。

注意 :我知道我不能删除,原因是 first() 方法)return 它到数组)

有什么办法吗?

Actually no need to use ->first(). Bcz your token is unique.

if you need try this.

$reset_row = DB::table('password_resets')->where('token', $request->token)
    ->Limit(1)->delete();

I think it is possible to use "limit" with "delete".

您可以简单地将删除方法链接到您的查询构建器。 不需要 select 第一个,因为你想删除它们,而不是 select 它们。

DB::table('password_resets')->where('token', $request->token)->delete();

它已经在 Whosebug 的另一个 post 中回答了。

你也可以使用这个答案 laravel-delete-query-builder and you can also look at the official documentation about deleting using the query builder

最后我想为重置密码创建模型并像这样使用它:

1. 通过在像 this

这样的模型上设置它来将主键设置为令牌

2.使用find方法查找token(document for find method)

这样使用:

$reset=PasswordReset::find($token);
//work with $reset
$reset->delete()

注意::要将主键设置为字符串 col,请参阅此