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();