【问题标题】:How would I do this query in laravel我将如何在 laravel 中进行此查询
【发布时间】:2015-06-09 19:24:46
【问题描述】:

如何在 laravel 查询生成器中执行此操作? (这基本上得到了你在投票系统中的当前位置)

SELECT position FROM 
    (SELECT participant.target_user_id, @rownum := @rownum + 1 as position FROM 
        (SELECT target_user_id, count(*) as votes FROM contest_participants_votes GROUP BY 
        target_user_id ORDER BY votes DESC) as participant 
    JOIN (SELECT @rownum := 0) r) x
WHERE target_user_id = 1

【问题讨论】:

  • 不清楚。这段代码有什么问题?
  • 这是纯 SQL,我想在 laravel 查询生成器中这样做,所以我不必考虑 sql 注入。
  • @user3542112 使用 target_user_id = ? 等占位符可以防止注入。
  • 那么我应该使用原始语句吗?

标签: mysql laravel query-builder


【解决方案1】:

我们使用这样的原始语句和占位符

$position = \DB::select(\DB::raw(
            'SELECT position FROM 
                (SELECT participant.target_user_id, @rownum := @rownum + 1 as position FROM 
                  (SELECT target_user_id, count(*) as votes FROM contest_participants_votes GROUP BY 
                  target_user_id ORDER BY votes DESC) as participant 
                JOIN (SELECT @rownum := 0) r) x
            WHERE target_user_id = ?'), [$pid]);

【讨论】:

  • \DB::select(\DB::raw('query'), $attributes) 应该是这样的,我猜。
  • 这个和raw有什么区别?我已经测试过它有效。我只需要做 $position[0]->position 来获得价值
  • raw 返回一个对象,select 实际执行的是查询。但是,当您不使用 raw 包装原始查询时,select 将尝试使用该字符串作为列名。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-30
  • 2020-05-09
  • 1970-01-01
  • 1970-01-01
  • 2020-05-21
相关资源
最近更新 更多