Eloquent MYSQL statement : WHERE NOT(A OR B)

2019-07-20 12:47发布

I`m working on date-range-overlap functionality that can be written in 13 positive conditions to check if the date intervals overlap :

https://en.wikipedia.org/wiki/Allen%27s_interval_algebra

Or more elegantly in 2 negative conditions:

http://baodad.blogspot.nl/2014/06/date-range-overlap.html

In MYSQL :

WHERE NOT(`last_day` <= '2001-06-01' OR `first_day` >= '2022-12-01');

This would require something like this, which I can`t find in the docs:

$query = $query->whereNot(function ($query) use ($first_day, $last_day) {
   $query->where('last_day', '<=', $first_day);
   $query->orWhere('first_day', '<=', $last_day);
});

How can I solve this?

This is related to my other possibly duplicate post : Laravel / Eloquent WHERE NOT SUBQUERY

But I hope my question is more clear now.

1条回答
Viruses.
2楼-- · 2019-07-20 13:04

You can achieve what you need by reverting the constraints on last_day and first_day - this way there is no need to use NOT clause.

Instead of doing

WHERE NOT(`last_day` <= '2001-06-01' OR `first_day` >= '2022-12-01');

you can do

WHERE `last_day` > '2001-06-01' AND `first_day` < '2022-12-01';

And with Eloquent builder the following should do the trick:

$query = $query->where('last_day', '>', $first_day)->where('first_day', '>', $last_day);
查看更多
登录 后发表回答