简体   繁体   English

Laravel Eloquent 查询生成器与包装的“位置”没有关系

[英]Laravel Eloquent query builder no relation on wrapped 'where'

I have made a package for searching models with JSON input which has a search macro exposed on Eloquent models.我制作了一个package 用于搜索具有 JSON 输入的模型,该输入具有在 Eloquent 模型上暴露的search宏。

While trying to wrap a query, I noticed a strange behavior, so I am wondering if I am doing something wrong.在尝试包装查询时,我注意到一个奇怪的行为,所以我想知道我是否做错了什么。

For example, loading the relation like this:例如,像这样加载关系:

Builder::macro('search', function () {
    return $this->with('someRelation');
});

results in all models with their relation being loaded, all looking good.结果是所有模型的关系都被加载了,看起来都很好。

Wrapping it within additional where clause causes it to load only models and no relation whatsoever:将其包装在附加的where子句中会导致它仅加载模型而不加载任何关系:

Builder::macro('search', function (array $input) {
    return $this->where(function (Builder $builder) {
        $builder->with('someRelation');
    });
});

Why doesn't this work?为什么这不起作用? How to make it load relation while wrapped within an outer where ?如何在包裹在外部where时使其加载关系?

I couldn't explain the specifics of why it doesn't work, but I'd imagine one of the following two options will fix it:我无法解释为什么它不起作用的细节,但我想以下两个选项之一可以解决它:

Builder::macro('search', function (array $input) {
    return $this->where(function (Builder $builder) {
        return $builder->with('someRelation'); // note added 'return'
    });
});

or或者

Builder::macro('search', function (array $input) {
    return $this->where(function (Builder $builder) {
        // return whatever
    })->with('someRelation');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM