【发布时间】: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