Laravel 3中的用户定义的MySQL变量? [英] User-defined MySQL variables in Laravel 3?
问题描述
我想使用用户定义的变量用顺序号更新一组MySQL记录的等级".以下查询可通过MySQL命令行正常运行:
I want to update the "rank" for a group of MySQL records with sequential numbers using a user-defined variable. The following query runs fine via the MySQL command line:
SET @rank:=0; UPDATE scores SET rank=@rank:=@rank+1 WHERE game_id=4 ORDER BY score DESC
但是,如果我尝试使用Laravel将其作为Fluent查询运行,则会失败.
But if I try and run it as a Fluent query using Laravel, it fails.
DB::query("SET @rank:=0; UPDATE scores SET rank=@rank:=@rank+1 WHERE game_id=4 ORDER BY score DESC");
错误消息:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL
syntax; check the manual that corresponds to your MySQL server version for the right
syntax to use near 'UPDATE scores SET rank=@rank:=@rank+1 WHERE game_id=4 ORDER BY' at line 1
SQL: SET @rank:=0; UPDATE scores SET rank=@rank:=@rank+1 WHERE game_id=4 ORDER BY score DESC
Bindings: array (
)
[已解决]
DB :: raw()来解救!以下作品:
DB::raw() to the rescue! The following works:
DB::query(DB::raw("SET @rank:=0"));
DB::query("UPDATE scores SET rank=@rank:=@rank+1 WHERE game_id=4 ORDER BY score DESC");
推荐答案
不可能在一个查询中执行多个语句. Laravel在引擎盖下使用了PDO,可以防止这种情况的发生.您可以尝试通过2个查询调用此方法,因为@rank
在连接期间应该可用.
It is not possible to execute multiple statements in one query. Laravel uses PDO under the hood which prevents this. You could attempt to call this over 2 queries instead, since @rank
should be available for the duration of the connection.
DB::query("SET @rank:=0");
DB::query("UPDATE scores SET rank=@rank:=@rank+1 WHERE game_id=? ORDER BY score DESC", array(4));
这篇关于Laravel 3中的用户定义的MySQL变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!