在ThinkPHP8中实现多条件模糊搜索,可以使用where方法结合数组构建查询条件。以下是一个示例代码:
// 假设有一个搜索表单,提交的参数有name, email, status等
$name = Request::param('name', '');
$email = Request::param('email', '');
$status = Request::param('status', '');
// 构建查询条件数组
$where = [];
if (!empty($name)) {
$where[] = ['name', 'like', "%{$name}%"];
}
if (!empty($email)) {
$where[] = ['email', 'like', "%{$email}%"];
}
if (!empty($status)) {
$where[] = ['status', '=', $status];
}
// 使用模型查询数据
$users = User::where($where)->select();
在上述代码中,我们首先获取表单提交的搜索参数,然后根据每个参数构建查询条件。如果某个参数不为空,我们将其添加到查询数组中。最后,我们使用User模型的where
方法应用这些条件并执行查询。这样,只有当至少有一个搜索条件填写时,才会进行模糊搜索。