Home > Article > Backend Development > How to implement multi-condition fuzzy query in laravel, and the front-end selection query option can be empty!
How to implement multi-condition fuzzy query in laravel, and the front-end selection query option can be empty! For example, I have a product table here, and the search options include product name, product price, product origin, and product availability. These query conditions can be non-empty, but they are still empty. For example, I search for products with a price of 100 yuan that are already on the shelves. , the other two search options are empty, or I only query the listed products, and the other options are empty!
How to implement multi-condition fuzzy query in laravel, and the front-end selection query option can be empty! For example, I have a product table here, and the search options include product name, product price, product origin, and product availability. These query conditions can be non-empty, but they are still empty. For example, I search for products with a price of 100 yuan that are already on the shelves. , the other two search options are empty, or I only query the listed products, and the other options are empty!
<code>$handle = DB::table('table_name'); // 如果条件1为真的时候 $keywords1 && $handle->where('field_name','like','%' . $keywords1 . '%'); // 如果条件2为真的时候 $keywords2 && $handle->where('field_name','like','%' . $keywords2 . '%'); // 如果条件3为真的时候 ... // 获取数据 $handle->get(); </code>
If it is ORM:
<code>$handle = new Model(); // 如果条件1为真的时候 $keywords1 && $handle->where('field_name','like','%' . $keywords1 . '%'); // 如果条件2为真的时候 $keywords2 && $handle->where('field_name','like','%' . $keywords2 . '%'); // 如果条件3为真的时候 ... 一样的</code>
<code class="php">//画蛇添足下 $handle = \DB::table('table_name'); $where = '1=1 '; if($condition1) { $where.= ' and field_name like "%' . $keywords1 . '%"'; } elseif($condition2) { $where.= ' and field_name like "%' . $keywords2 . '%"'; } $res = $handle->whereRaw($where)->get(); </code>