how to get opposite results from a query Laravel

2019-04-17 05:33发布

问题:

How to get the opposite results from a SELECT query

Below is my query

  $fod = FodMap::select('*')
        ->where('fructose_level', $fructose == 1 ? '=' : '>=', $fructose)
        ->where('lactose_level', $lactose == 1 ? '=' : '>=', $lactose)
        ->where('polyols_level', $polyols == 1 ? '=' : '>=', $polyols)
        ->where('fructan_level', $fructan == 1 ? '=' : '>=', $fructan)
        ->get();

I want to get everything that doesn't fall under the above query. pls advice

回答1:

For making negative statement in Laravel use whereNotIn expression.

laravel.io



回答2:

Ok, I thought about your question for some time and I think the solution is not as complicated as you asked first (when I've read it first, I thought you want inverted result).

  1. In one of your comments you wrote:

above results gives the list of foods which user can't eat.. what i want it to get the results which not matching above

  1. I've read about fructose levels etc. In a nutshell, levels higher than 1 are bad, less than 1 are good.

So, solution is way too simple then:

$fod = FodMap::select('*')
        ->where('fructose_level', '<', $fructose)
        ->where('lactose_level', '<', $lactose)
        ->where('polyols_level', '<', $polyols)
        ->where('fructan_level', '<', $fructan)
        ->get();

Also, ternary operators in your original query do not make sense, because clause like:

->where('fructose_level', $fructose == 1 ? '=' : '>=', $fructose)

will always work as:

->where('fructose_level', '>=', $fructose)

Think about it.