如何用Laravel锁定table?

How to lock table with Laravel?

我想在交易中锁定 table。像这样:

  DB::transaction(function (){
    DB::statement('LOCK TABLES important_table WRITE');
    //....
  });

然而,行 DB::statement('LOCK TABLES important_table WRITE'); 总是触发以下错误:

SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active. Consider using PDOStatement::fetchAll(). Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute. (SQL: LOCK TABLES officeSeal WRITE)

如何在 Laravel 中锁定 table?

可以像这样在 Laravel 中锁定 table:

DB::raw('LOCK TABLES important_table WRITE');

正如其他用户在评论中指出的那样,我不确定 table 锁绝对是唯一的出路。但是,如果您坚持,可以使用 Laravel 的 Pessimistic Locking。即,sharedLock()lockForUpdate() 方法,如文档中所述。

您会注意到文档中的示例没有使用 Eloquent, but relies on Query Builder. However, this Q&A 似乎表明它也可以用 Eloquent 完成。

通读 this article 也是值得的,它对比了 Laravel 中的悲观和乐观锁定实现。

DB::毫无准备('LOCK TABLES important_table WRITE');这个对我有用