laravel querybuilder如何在wherein函数中使用like

laravel querybuilder how to use like in wherein function

$book = array('book1','book2'); $book 数组元素编号是可变的。它可能有 2 个元素或 20 个元素
我需要这样查询:

select * from book where bookname like %book1% or bookname like %book2%

要在 laravel 5 中进行此查询,有一个选项:

$name = DB::Table('bookinfo')
          ->select('*')
          ->wherein('bookname',$book)
          ->get();

但它使用 = 运算符 我需要使用 like 运算符

对于包含 1 个或 n 个元素的动态查询,请将您的语句用作集合: 对于 "like" 你可以使用原始语句:

$collection = DB::Table('bookinfo')->select('*');
foreach($book as $key => $element) {
    if($key == 0) {
        $collection->where(DB::raw('bookname like %'.$element.'%'));
    }
    $collection->orWhere(DB::raw('bookname like %'.$element.'%'));
}
$name = $collection->get();

http://laravel.com/docs/5.1/queries

Raw Expressions

或者你可以这样使用:

$collection = DB::Table('bookinfo')->select('*');
foreach($book as $key => $element) {
    if($key == 0) {
        $collection->where('bookname', 'like', '%'.$element.'%');
    }
    $collection->orWhere('bookname', 'like', '%'.$element.'%');
 }
 $name = $collection->get();
$name = DB::Table('bookinfo')
          ->select('*')
          ->where('bookname','LIKE','%'.$book[0].'%')
          ->orWhere('bookname','LIKE','%'.$book[1].'%')
          ->get();

感谢大家帮助我,但我通过这样做解决了它:

$book = array('book2','book3','book5');  

$name = DB::Table('bookinfo')
        ->select('BookName', 'bookId')                
        ->Where(function ($query) use($book) {
             for ($i = 0; $i < count($book); $i++){
                $query->orwhere('bookname', 'like',  '%' . $book[$i] .'%');
             }      
        })->get();