【问题标题】:Laravel where exists query issue / not workingLaravel 存在查询问题/不工作
【发布时间】:2015-10-01 23:43:09
【问题描述】:

好的,所以我有一个项目表,其中可以存在具有相同“parent_uuid”的重复项目,可以“发布”或“丢弃”。我正在尝试获取一组“已丢弃”的项目,其中已发布为 0,但没有重复行与已发布标记为 1 的相同“parent_uuid”。

当我在 sql 中编写查询时,它的行为正确:

SELECT * FROM `items` AS `items` WHERE `published` = 0 AND `created_at` < '2015-08-30 17:23:29' AND NOT EXISTS (SELECT 1 FROM `items` AS `check` WHERE `check`.`parent_uuid` = `items`.`parent_uuid` AND `published` = 1) GROUP BY `parent_uuid`

我的测试用例按预期返回。当我在 Laravel 查询生成器中这样写时:

  $discarded = self::from('items as items')
    ->where('published', 0)
    ->where('created_at', '<', Carbon::now()->subMonth()->toDateTimeString())
    ->whereNotExists(function($query) {
      $query->select(DB::raw(1))
        ->from('items as check')
        ->where('check.parent_uuid', 'items.parent_uuid')
        ->where('published', 1);
    })
    ->groupBy('parent_uuid');

我得到的结果比我预期的要多。我得到了应该失败 where not exists 子查询的项目的结果。当我输出最后一个查询时,一切看起来都很好。如果我将此查询复制到我的 sql 客户端并交换变量,它会按我的预期工作。

array (size=3)
  'query' => string 'select * from `items` as `items` where `published` = ? and `created_at` < ? and not exists (select 1 from `items` as `published` where `published`.`parent_uuid` = ? and `published` = ?) group by `parent_uuid`' (length=211)
  'bindings' => 
    array (size=4)
      0 => int 0
      1 => string '2015-08-30 17:23:29' (length=19)
      2 => string 'items.parent_uuid' (length=22)
      3 => int 1
  'time' => float 442.8

我不确定自己做错了什么,我已经尝试了几乎所有我能想到的。

有人知道这里会发生什么吗?我在 Laravel 4.2 上。

【问题讨论】:

    标签: php mysql laravel-4 query-builder


    【解决方案1】:

    问题似乎与 Laravel 的查询构建器有关,并且可能与数据库驱动程序有关。这可能是我目前拥有的库的构建的临时问题。

    我为这些情况找到的解决方案是创建原始数据库字符串并将其通过管道传输到高级 where select 查询。你可以这样做:

      $where_not_exists = '1 FROM `items` AS `check` WHERE `check`.`parent_uuid` = `items`.`parent_uuid` AND `published` = 1';
    
      $discarded = Items::from('items as items')
        ->where('published', 0)
        ->where('created_at', '<', Carbon::now()->subMonth()->toDateTimeString())
        ->whereNotExists(function($query) use ($where_not_exists) {
          $query->select(DB::raw($where_not_exists));
        })
        ->groupBy('parent_uuid');
    
      if ($count === TRUE) {
        return $discarded->count();
      }
    
      return $discarded->get();
    

    这不是非常难以阅读。只要确保永远不要将用户发送的输入直接注入这些!

    【讨论】:

      猜你喜欢
      • 2012-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-27
      • 1970-01-01
      • 1970-01-01
      • 2015-12-16
      相关资源
      最近更新 更多