在执行wherehas的地方执行时的奇怪行为

时间:2018-02-14 07:49:25

标签: php laravel

在whereHas函数中执行where子句时,我遇到了一些奇怪的行为。如果运行以下内容:

uuid param是:' 96914c50-0c36-11e8-8819-e174932b5901';

...    
$this->builder->whereHas('document.group', function ($q) use ($uuid) {
           return $q->where('uuid', $uuid);
        });
...

生成的查询是:

SELECT * FROM `comments` WHERE exists (SELECT * FROM `documents` WHERE `comments`.`document_id` = `documents`.`id` and `uuid` = '1')

注意uuid被解析为1。 要明确的是,当我在我的whereHas中var_dump $ uuid时,我仍然会收到正确的值。

所以我继续尝试以下内容:

...
    $group = DocumentGroup::where('uuid', $uuid)->value('id');

            $this->builder->whereHas('document', function ($q) use ($group) {
                $q->whereHas('group', function ($q) use ($group) {
                    return $q->where('uuid', $group);
                });
            });
...

在我的第二个whereHas中,$ group的值是2755,这是正确的id。

但是得到的sqls是:

SELECT `id` FROM `document_groups` WHERE `uuid` = '96914c50-0c36-11e8-8819-e174932b5901' LIMIT 1

SELECT * FROM `comments` WHERE exists (SELECT * FROM `documents` WHERE `comments`.`document_id` = `documents`.`id` and exists (SELECT * FROM `document_groups` WHERE `documents`.`group_id` = `document_groups`.`id` and `uuid` = '1'))

同样,id被解析为1.有没有人知道为什么会这样?

更新:

经过多次测试后,结果甚至更奇怪了。

以下代码:

...
$this->builder->whereHas('document', function ($q) use ($uuid) {
            $q->whereHas('group', function ($q) use ($uuid) {
                $q->where('title', '=', "ole");
            });
        });
...

提供以下sql:

SELECT count(*) as aggregate FROM `comments` WHERE exists (SELECT * FROM `documents` WHERE `comments`.`document_id` = `documents`.`id` and exists (SELECT * FROM `document_groups` WHERE `documents`.`group_id` = `document_groups`.`id` and `title` = '1'))

UPDATE2:

我已修复'它通过使用whereRaw而不是where:

$this->builder->whereHas('document', function ($q) use ($uuid) {
            $q->whereHas('group', function ($q) use ($uuid) {
                return $q->whereRaw('uuid = "' . $uuid . '"');
            });
        });

SELECT * FROM `comments` WHERE exists (SELECT * FROM `documents` WHERE `comments`.`document_id` = `documents`.`id` and exists (SELECT * FROM `document_groups` WHERE `documents`.`group_id` = `document_groups`.`id` and uuid = "96914c50-0c36-11e8-8819-e174932b5901"))

0 个答案:

没有答案