How to implement multi-condition fuzzy query in laravel, and the front-end selection query option can be empty!

WBOY
Release: 2023-03-03 08:32:01
Original
1702 people have browsed it

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!

Reply content:

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>
Copy after login

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>
Copy after login

<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>
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template