Reputation: 28968
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:
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)
How can I lock the table in Laravel?
Upvotes: 9
Views: 26613
Reputation: 28968
One can lock a table in Laravel like this:
DB::statement(DB::raw('LOCK TABLES important_table WRITE'))
;
However, you should be aware that locking a table is not very performant and row-locking should be used instead if possible.
Upvotes: 15
Reputation: 39
DB::unprepared('LOCK TABLES important_table WRITE'); this one worked for me
Upvotes: 1
Reputation: 1346
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.
You'd notice that the example in the documentation doesn't use Eloquent, but relies on Query Builder. However, this Q&A seems to suggest that it can be done with Eloquent too.
It may also be worthwhile to have a read through this article which contrasts Pessimistic and Optimistic locking implementations in Laravel.
Upvotes: 4