php - Laravel 中的 whereHas 查询

标签 php laravel laravel-5 laravel-5.2

大家好,

        $filterArray = explode("_", $filters);

        $data['articles'] = \DB::table('products')->join('product_category', function ($q) {
            $q->on('product_category.product_id', '=', 'products.id');
        })->where('product_category.category_id', '=', $id)
            ->select('products.*')
            ->whereBetween('price_retail_1', array($priceFrom, $priceTo))
            ->whereHas('filters', function ($query, $filterArray) {
                $query->whereIn('filter_id', $filterArray);
            })
            ->orderBy('products.' . $sort, $sortOrder)
            ->get();
    }

我有以下查询,并且在 whereHas 方法上遇到了一些问题。我收到一个错误
Unknown column 'has' in 'where clause

很可能是因为 $filterArray 变量超出了函数的范围(或者至少这是我的猜测。有关如何解决问题的任何帮助表示赞赏。

最佳答案

您不能使用 whereHas查询生成器上下文中的方法。 whereHas方法仅适用于 Eloquent 来自 Eloquent 模型及其关系的查询生成器。

你可以做的是使用joins .所以你可以这样尝试:

$filterArray = explode("_", $filters);

$data['articles'] = \DB::table('products')->join('product_category', function ($q) {
        $q->on('product_category.product_id', '=', 'products.id');
    })->where('product_category.category_id', '=', $id)
        ->select('products.*')
        ->whereBetween('price_retail_1', array($priceFrom, $priceTo))
        ->join('filters', 'products.filter_id', '=', 'filters.filter_id')
        ->whereIn('filter_id', $filterArray);
        ->orderBy('products.' . $sort, $sortOrder)
        ->get();

我不知道你是如何连接这两个表的,所以这里只是示例数据:
->join('filters', 'products.filter_id', '=', 'filters.filter_id')

关于php - Laravel 中的 whereHas 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39711486/

相关文章:

php - 如何在写入 MySQL 数据库时处理撇号

php - 搜索数组: array_filter vs loop

php - 有没有办法让 VS code 模仿 Dreamweaver 使用 PHP 显示数据库结果的简单方法

php - Laravel Echo + Laravel Passport + CORS

php - Laravel 5.1.19 artisan 制作 :auth is not available

php - 使用 PHP 解析 XML 获取属性值?

php - 在 Laravel 5.x 中为 trans() 组织本地化文件的好策略是什么?

php - 为什么我的 Laravel 4 种子脚本会生成不正确的插入查询?

Laravel 5.6 - 在此服务器上找不到请求的资源/home

php - 如何使用中介来连接 Laravel 中的表?