php - 拉维尔 : advanced search form query

标签 php laravel query-builder

我有一个高级搜索表单,可以使用 Laravel 从数据库中过滤出结果。数据已正确过滤,但我要求用户能够使用相同的文本框(以高级形式)按名字或姓氏进行过滤。我尝试 orWhere 以确保它使用名字或姓氏过滤名称字段,但 orWhere 不考虑其他过滤器。我使用的代码如下:

DB::table('mytable')
                ->where(function($query) use ($name, $degree_s, $specialty_s, $city_s, $state_s, $lundbeck_id_s) {

                if ($name)
                    $query->where('first_name', 'like', "$name%")->orWhere('last_name', 'like', "$name%"); # this is whats causing the issue
                if ($specialty_s)
                    $query->where('primary_specialty', $specialty_s);
                if ($city_s)
                    $query->where('city', $city_s);
                if ($state_s)
                    $query->where('state_province', $state_s);
                if ($lundbeck_id_s)
                    $query->where('customer_master_id', $lundbeck_id_s);
                if ($degree_s)
                    $query->where('primary_degree', $degree_s);
                })

                ->select('id', 'first_name','last_name')

添加 orWhere 子句会导致查询不使用其他条件(如 city_s 或 state_s)。

最佳答案

你需要改变:

if ($name)
   $query->where('first_name', 'like', "$name%")->orWhere('last_name', 'like', "$name%");

进入:

if ($name) {
   $query->where(function($q) use ($name) {
         $q->where('first_name', 'like', "$name%")->orWhere('last_name', 'like', "$name%");
   });
}

让 Laravel 添加括号,这样它就会像你期望的那样工作。

编辑

当然你不需要在这里用闭包包装所有东西,所以最好的解决方案是:

<?php

$query = DB::table('mytable')->select('id', 'first_name', 'last_name');

if ($name) {
    $query->where(function ($q) use ($name) {
        $q->where('first_name', 'like', "$name%")
            ->orWhere('last_name', 'like', "$name%");
    });
}
if ($specialty_s) {
    $query->where('primary_specialty', $specialty_s);
}
if ($city_s) {
    $query->where('city', $city_s);
}
if ($state_s) {
    $query->where('state_province', $state_s);
}
if ($lundbeck_id_s) {
    $query->where('customer_master_id', $lundbeck_id_s);
}
if ($degree_s) {
    $query->where('primary_degree', $degree_s);
}

$data = $query->get();

关于php - 拉维尔 : advanced search form query,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26972963/

相关文章:

php - 无法使用嵌套的 while 循环执行准备好的语句

php - 我如何让我的 Android 应用程序向 sqlserver 发送和接收数据/信息

php - Ajax 调用返回 301 永久移动突然

sql-server - 适用于 Microsoft SQL Server 的开源查询生成器工具

Yii2 ActiveQuery 'OR LIKE' 过滤器

symfony - Doctrine queryBuilder where IN 集合

php - 将表单变量传递到 Php 查询

javascript - Laravel 5.5 artisan 服务器上的 AJAX 404 错误

php - Laravel 数据透视表在数据库中为空

php - 在 float LARAVEL 上调用成员函数 addEagerConstraints()