如何使用 Laravel 锁定表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/53522444/
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
How to lock table with Laravel?
提问by Adam
I want to lock a table inside a transaction. Something like this:
我想在事务中锁定一个表。像这样的东西:
DB::transaction(function (){
DB::statement('LOCK TABLES important_table WRITE');
//....
});
However, the line DB::statement('LOCK TABLES important_table WRITE');
always triggers the following error:
但是,该行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)
SQLSTATE[HY000]:一般错误:2014 无法执行查询,而其他无缓冲查询处于活动状态。考虑使用 PDOStatement::fetchAll()。或者,如果您的代码只针对 mysql 运行,您可以通过设置 PDO::MYSQL_ATTR_USE_BUFFERED_QUERY 属性来启用查询缓冲。(SQL: LOCK TABLES officeSeal WRITE)
How can I lock the table in Laravel?
如何在 Laravel 中锁定表?
回答by Adam
One can lock a table in Laravel like this:
你可以像这样在 Laravel 中锁定一张表:
DB::raw('LOCK TABLES important_table WRITE')
;
DB::raw('LOCK TABLES important_table WRITE')
;
回答by Dhruv Saxena
As pointed out in the comments by other users too, I don't feel certain that a table lock is absolutely the only way out. However, if you insist, you could use Laravel's Pessimistic Locking. Namely, sharedLock()
and lockForUpdate()
methods, as mentioned in the documentation.
正如其他用户在评论中也指出的那样,我不确定表锁是否绝对是唯一的出路。然而,如果你坚持,你可以使用 Laravel 的悲观锁定。即sharedLock()
和lockForUpdate()
方法,如文档中所述。
You'd notice that the example in the documentation doesn't use Eloquent, but relies on Query Builder. However, this Q&Aseems to suggest that it can be done with Eloquent too.
您会注意到文档中的示例没有使用Eloquent,而是依赖于Query Builder。然而,这个问答似乎表明它也可以用 Eloquent 来完成。
It may also be worthwhile to have a read through this articlewhich contrasts Pessimistic and Optimistic locking implementations in Laravel.