【问题标题】:SQL/Laravel - Why does my query returns an empty collection?SQL/Laravel - 为什么我的查询返回一个空集合?
【发布时间】:2017-12-01 11:31:49
【问题描述】:

我的 Laravel 查询生成器返回一个空集合,而 SQL 字符串本身在 phpmyadmin 中执行时返回正确的记录。

这是我的代码:

$times = Time::join(\DB::raw('(SELECT `ath_id`, `stroke_id`, MIN(time) AS time FROM times GROUP BY ath_id, stroke_id) b'), function($join) {
                 $join->on('times.ath_id', '=', 'b.ath_id')
                      ->where('times.stroke_id', '=', 'b.stroke_id')
                      ->where('times.time', '=', 'b.time');
             })
             ->where('times.ath_id', '=', $id)
             ->orderBy('times.stroke_id', 'ASC')
             ->orderBy('times.date', 'DESC');
dd($times->get());

以下是在 phpmyadmin 中工作的 sql,但不适用于 laravel 查询构建器。另外,这是使用dd($times->toSql());时返回的SQL字符串(其中$times->getBindings()返回['b.stroke_id', 'b.time', '4298584']填写问号?

SELECT * FROM `times`
INNER JOIN (SELECT `ath_id`, `stroke_id`, MIN(time) AS time
            FROM times GROUP BY ath_id, stroke_id) b
ON `times`.`ath_id` = `b`.`ath_id`
    ADN `times`.`stroke_id` = b.stroke_id -- ?
    AND `times`.`time` = b.time -- ?
WHERE `times`.`ath_id` = 4298584 -- ?
ORDER BY `times`.`stroke_id` asc, `times`.`date` desc

【问题讨论】:

    标签: mysql sql laravel laravel-query-builder


    【解决方案1】:

    这有点“棘手”。您在 phpmyadmin 中执行的查询确实是正确的。但是,Laravel 以不同的方式使用 where()on()

    在处理列时使用where()on()

    $times = Time::join(\DB::raw('(SELECT `ath_id`, `stroke_id`, MIN(time) AS time FROM times GROUP BY ath_id, stroke_id) b'), function($join) {
                     $join->on('times.ath_id', '=', 'b.ath_id')
                          ->on('times.stroke_id', '=', 'b.stroke_id')
                          ->on('times.time', '=', 'b.time');
                 })
                 ->where('times.ath_id', '=', $id)
                 ->orderBy('times.stroke_id', 'ASC')
                 ->orderBy('times.date', 'DESC');
    

    文档:https://laravel.com/docs/5.4/queries,部分 (CTRL+F):高级连接

    如果您想在连接中使用“where”样式子句,您可以在连接上使用whereorWhere 方法。这些方法不是比较两列,而是将列与一个值进行比较。

    为了更清楚一点:

    $join->on('times.ath_id', '=', 'b.auth_id')->where('times.stroke_id', '=','b.stroke_id');
    

    结果:

    JOIN on `times`.`ath_id` = `b`.`auth_id` WHERE `times`.`stroke_id` = 'b.stroke_id' -- AS STRING
    

    toSql() 返回您的查询并且您认为Laravel 知道:

    ['b.stroke_id', 'b.time', '4298584']
    

    前两个绑定绑定是列。但是where() 认为它们只是字符串。

    【讨论】:

    • 这说明了一切!它确实让我感到困惑。我想我完全阅读了that page。但这对我来说并不清楚。
    • @DerkJanSpeelman 有一次我花了一天时间试图弄清楚我的查询出了什么问题。有同样的问题:在 phpmyadmin 中执行它给了我我想要的东西,但是我在 Laravel 中得到一个空结果......
    • @IvankaTodorova 我想知道哪个 PHP 平台用于提供服务和联系人们的网站。 . .
    猜你喜欢
    • 2021-06-15
    • 2021-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-06
    相关资源
    最近更新 更多