【问题标题】:Laravel query builder returning empty where direct SQL returns resultsLaravel 查询生成器在直接 SQL 返回结果的地方返回空
【发布时间】:2014-07-08 00:24:38
【问题描述】:

我正在尝试解决一个问题,即使用 Laravel 的查询生成器我没有得到任何结果,但是当我运行相同的查询时,使用 PHPMyAdmin 从 getQueryLog 获取我得到预期的结果。

我的查询生成器:

DB::table('likes')
            ->join('geoip_blocks', function($join)
            {
                $join->where("ip", ">=", "block_start")
                    ->where("ip", "<=", "block_end");
            })
            ->join('geoip_locations', "geoip_locations.id", "=", "location_id")
            ->select(array("country", DB::raw("count(*) as {$this->aggregate}")))
            ->groupBy('country')->get();

查询日志的输出:

array (size=3)
  'query' => string 'select `country`, count(*) as count from `likes` inner join `geoip_blocks` on `ip` >= ? and `ip` <= ? inner join `geoip_locations` on `geoip_locations`.`id` = `location_id` group by `country`' (length=196)
  'bindings' => 
    array (size=2)
      0 => string 'block_start' (length=11)
      1 => string 'block_end' (length=9)
  'time' => float 2.69

以及我在 phpmyadmin 中输入的查询:

select `country`, count(*) as count from `likes` inner join `geoip_blocks` on `ip` >= block_start and `ip` <= block_end inner join `geoip_locations` on `geoip_locations`.`id` = `location_id` group by `country`

我知道上面的查询效率极低。这只是为了证明概念,它甚至不起作用,所以为什么还要走得更远。我尝试了不同程度的模棱两可和明确性无济于事。还尝试删除第二个连接并仅获取 location_id - 再次没有成功。

非常感谢任何帮助!

【问题讨论】:

  • 你到底为什么不使用 Eloquent???
  • 与 Eloquent 相同。我使用查询生成器进行了尝试,因为 Eloquent 不起作用!
  • 好吧,如果其他一切都失败了,你总是可以使用带有绑定参数的旧 PDO。

标签: php mysql sql laravel eloquent


【解决方案1】:

好的,所以我想通了。我将$join-&gt;where 都切换为$join-&gt;on,现在一切正常。从表面上看,它会生成相同的查询,但我猜幕后还有其他事情发生。

【讨论】:

  • 是的,JoinClause 类上的where 应该用于固定值,而on 用于其他列。您的第一次尝试将block_startblock_end 视为要比较的字符串而不是列。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-25
  • 1970-01-01
  • 2014-08-03
  • 2016-12-17
相关资源
最近更新 更多