0

For a model I have a complicated scope condition like so:

class Foo {
    public function scopeActive(Builder $query) {
        $dateNow = $now->format('Y-m-d');
        $timeNow = $now->second(0)->format('H:i:s');
        $query->whereNull('start_date')
            ->orWhere('start_date', '<', $dateNow)
            ->orWhere(function (Builder $query) use ($dateNow, $timeNow) {
                 $query->where('start_date', '=', $dateNow)
                     ->where('start_time', '>=', $timeNow);
            });
    }
}

This complicated condition will select all the records in Foo that are considered active (the real scope is even more complicated than that).

I have another class like so:

class Bar {
    public function foos() {
        return $this->hasMany(Foo::class);
    }
}

Which means the Bar model has many Foo models.

Now if I wanted to get all the Bar models as well as all the active Foo models that belong to it, I can do the following:

Bar::with(['foo', function (HasMany $query) {
    $query->active();
})->get();

However, how can I write a query that gives me all the Bar records that are NOT active.

Ideally I would want something like this:

Bar::with(['foo', function (HasMany $query) {
    $query->whereNot(function (Builder $query) {
        $query->active();
    });
})->get();
4

2 回答 2

0

似乎没有一种有效的方法可以使用 Laravel 轻松反转 SQL 以进行复杂的查询。

你只需要写逆。

于 2017-03-01T10:33:48.080 回答
0

如果您想拥有一个相反的范围,只需像这样创建另一个范围方法,但使用反向查询逻辑(您没有包括“一些复杂的查询”,所以这只是一个猜测):

public function scopeInactive($query) {
    return $query->where('is_active', false);
}

Laravel:本地范围

于 2017-02-03T10:41:09.073 回答