php - Laravel where 子句在多个 orWhere 子句后不起作用?

标签 php mysql laravel laravel-5 eloquent

我正在查询具有型号名称和类型的车辆,但这些 where 子句在添加 orWhere 后并未在末尾。当我评论或删除这些 orWhere 子句时,它就起作用了。

$models = Vehicle::join('vmodels', 'vmodels.vehicle_id', '=', 'vehicles.id')
    ->join('vehicletypes', 'vehicletypes.id', '=', 'vehicles.vehicletype_id')
    ->join('brands', 'brands.id', '=', 'vehicles.make')
    ->join('companies', 'brands.id', '=', 'companies.name')
    ->select('vehicles.slug as vslug', 'brands.name as brandname', 'vehicles.id as vid', 'vmodels.*', 'vehicletypes.name as vtype', 'companies.status as cstatus')
    ->where('brands.name', 'LIKE', "%{$term}%")
    ->orWhere('vmodels.name', 'LIKE', "%{$term}%")
    ->orWhere('vmodels.year', 'LIKE', "%{$term}%")
    ->orWhere('vehicletypes.name', 'LIKE', "%{$term}%")
    ->orWhere('vehicles.model', 'LIKE', "%{$term}%")
    ->where('companies.status', '=', 1 )
    ->where('vmodels.status', '=', 1)
    ->where('vehicles.status', '=', 1)
    ->paginate(30);

最佳答案

将你的 orWhere 放在一起,

$models = Vehicle::join('vmodels', 'vmodels.vehicle_id', '=', 'vehicles.id')
    ->join('vehicletypes', 'vehicletypes.id', '=', 'vehicles.vehicletype_id')
    ->join('brands', 'brands.id', '=', 'vehicles.make')
    ->join('companies', 'brands.id', '=', 'companies.name')
    ->select('vehicles.slug as vslug', 'brands.name as brandname', 'vehicles.id as vid', 'vmodels.*', 'vehicletypes.name as vtype', 'companies.status as cstatus')
    ->where(function($query) use($term){
        $query->where('brands.name', 'LIKE', "%{$term}%")
            ->orWhere('vmodels.name', 'LIKE', "%{$term}%")
            ->orWhere('vmodels.year', 'LIKE', "%{$term}%")
            ->orWhere('vehicletypes.name', 'LIKE', "%{$term}%")
            ->orWhere('vehicles.model', 'LIKE', "%{$term}%");
    })
    ->where('companies.status', '=', 1 )
    ->where('vmodels.status', '=', 1)
    ->where('vehicles.status', '=', 1)
    ->paginate(30);

引用:https://laravel.com/docs/5.7/queries#parameter-grouping

关于php - Laravel where 子句在多个 orWhere 子句后不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54303568/

相关文章:

php - 尝试将托管 Web 应用程序连接到本地数据库?

php - DOM 解析器是如何实现的?

mysql - 为什么数据库中不存在该表

类不存在

PHP将数据存储到mysql数据库时出现语法错误

PHP AJAX 加载更多

php - PDO 准备语句未返回预期结果

php - Internet Explorer 未在链选择上显示 <option> 值

php - Eloquent 查询来搜索两个表

php - 从最近 20 条记录中随机返回 5 条记录