Multiple column with same search string in laravel

2019-08-09 08:41发布

问题:

SELECT * 
FROM table_name 
WHERE 
    CONCAT(id,name, address) LIKE '%same_string%' 

What is an alternate query for this in Laravel

回答1:

Try this.

$field = ['name','id','address'];
$name = DB::Table('bookinfo')->Where(function ($query) use($string, $field) {
             for ($i = 0; $i < count($field); $i++){
                $query->orwhere($field, 'like',  '%' . $string .'%');
             }      
        })->get();


回答2:

** Laravel - The general search in multiple columns the in single input

**

one of the user table in the first name, last name, job title column available and I have one input search in any value enter then find all column in associated data fetch and display

 $searchQuery = trim($request->query('search'));
 $requestData = ['firstname', 'lastname', 'job_title'];
  $user = User::where(function($q) use($requestData, $searchQuery) {
                        foreach ($requestData as $field)
                           $q->orWhere($field, 'like', "%{$searchQuery}%");
                })->get();


回答3:

Try this for separate column

DB::table("table_name")->whereRaw(" (`id` like ? or `name` like ? or `address` like ? ) ",["%".$same_string."%","%".$same_string."%","%".$same_string."%"])->get();