【问题标题】:WhereIn in Query doesn't work for array, Any solution?Query 中的 WhereIn 不适用于数组,有什么解决方案吗?
【发布时间】:2020-04-27 03:53:56
【问题描述】:

我在 Model 中定义了scopeFilter,代码如下

public function scopeFilter($query, array $filters){
    $query->when($filters['subjects'] ?? null, function ($query, $data) {
        //Subjects ids will be comma seperated string eg : 127,125
        $subject_array = explode(',', htmlspecialchars_decode($data))
        $query->where(function ($query) use ($subject_array) {
            $query->whereIn('subjects_ids', $subject_array);
        });
    });
    $query->when($filters['topics'] ?? null, function ($query, $data) {
        //topics ids will be comma seperated string eg : 127,125
        $topic_array = explode(',', htmlspecialchars_decode($data))
        $query->where(function ($query) use ($topic_array) {
            $query->whereIn('topics_ids', $topic_array);
        });
    });
    $query->when($filters['search'] ?? null, function ($query, $search) {
        $query->where(function ($query) use ($search) {
            $query->where('name', 'like', '%'.$search.'%');
        });
    });
}

这是我在控制器中的使用方式

$exams = Exams::filter(\Request::only('search', 'subjects','topics'))
            ->orderBy('status', 'DESC')
            ->orderBy('updated_at', 'DESC')->transform(....);

如果这是在 url 查询中传递的,那么结果将为空。我在这里做错什么了吗?

基本上是三个过滤器,搜索工作正常,但主题和主题不起作用。

【问题讨论】:

    标签: laravel laravel-5 eloquent laravel-query-builder


    【解决方案1】:

    您没有在函数中返回 $queryLaravel Local Scope

    public function scopeFilter($query, array $filters){
        $query->when($filters['subjects'] ?? null, function ($query, $data) {
            //Subjects ids will be comma seperated string eg : 127,125
            $subject_array = explode(',', htmlspecialchars_decode($data))
            $query->where(function ($query) use ($subject_array) {
                $query->whereIn('subjects_ids', $subject_array);
            });
        });
        $query->when($filters['topics'] ?? null, function ($query, $data) {
            //topics ids will be comma seperated string eg : 127,125
            $topic_array = explode(',', htmlspecialchars_decode($data))
            $query->where(function ($query) use ($topic_array) {
                $query->whereIn('topics_ids', $topic_array);
            });
        });
        $query->when($filters['search'] ?? null, function ($query, $search) {
            $query->where(function ($query) use ($search) {
                $query->where('name', 'like', '%'.$search.'%');
            });
        });
        return $query;
    }
    

    希望对你有帮助:)

    【讨论】:

      【解决方案2】:

      认为你错过了 scopeFilter 中的return

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-12-17
        • 1970-01-01
        • 2014-11-14
        • 1970-01-01
        • 2021-07-27
        • 2011-08-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多