简体   繁体   中英

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.

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:

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 ?

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');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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