简体   繁体   中英

How to use MY SQL IN operator with where clause in laravel 5.4?

Can any one help me with that issue please.

I need to use MY-SQL (IN) operator within where clause in laravel 5.4, I have columns variable which is a variable length array holding columns names called "$cols" so I can not use "whereIn" cause I don't know the count of my conditions colomns here's my code

    conditions = [];
    if(!is_null($cols)){
        for($i = 0; $i < count($cols); $i++){
            $vals = explode("-", $values[$i]);
            $conditions[] = [$cols[$i], 'IN', $values[$i]];
        }
    }
    $data = DB::table('my_table')->where($conditions)->orderBy('id','desc')->get();  

so any one can help me how to do something like that

Thaks

As per the documentation , you can use whereIn , eg:

$data = DB::table('my_table')
      ->where($conditions)
      ->whereIn('something', [val1, val2, val3])
      ->orderBy('id','desc')
      ->get();

Try something like this

$queryBuilder = DB::table('my_table');

if( ! empty($cols)){
    for($i = 0; $i < count($cols); $i++) {
      $vals = explode("-", $values[$i]);
      // adding whereIn() per column
      $queryBuilder->whereIn($cols[$i], $vals);
    }
}

$data = $queryBuilder
          ->orderBy('id','desc')
          ->get();

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