具有多个参数的多个 EloquentWhere 语句

问题描述 投票:0回答:2

我遇到一个解析问题,我想获取具有特定订阅的所有人员,而不是具有其他类型订阅的人员。订阅存储在订阅表的订阅列中以逗号分隔的列表中。这是我到目前为止的代码:

        $includeQuery = [];
        foreach ($includeSegment as $include) {
            $singleQuery = ['subscriptions','like', '%'.$include.'%', 'or'];
            array_push($includeQuery, $singleQuery);
        }
        $excludeQuery = [];
        foreach ($excludeSegment as $exclude) {
            $singleQuery = ['subscriptions', 'not like', '%'.$exclude.'%', 'or'];
            array_push($excludeQuery, $singleQuery);
        }

        $included = Subscription::where($excludeQuery)->where($includeQuery)->get();

我收到结果,但其中一些包含排除的订阅。

php laravel eloquent
2个回答
0
投票

使用 whereIn 和 whereNotIn 来代替 :

订阅::whereIn($includeSegment)->whereNotIn($excludeSegment)->get();

那么一旦它们是字符串数组,你就不需要迭代它们了


0
投票

上面代码的问题在于我用“or”而不是“and”的布尔参数。因此,只有当特定用户的所有订阅都存在时,记录才会被丢弃。这是更新后的代码:

        $includeQuery = [];
        foreach ($includeSegment as $include) {
            $singleQuery = ['subscriptions','like', '%'.$include.'%', 'or'];
            array_push($includeQuery, $singleQuery);
        }
        $excludeQuery = [];
        foreach ($excludeSegment as $exclude) {
            $singleQuery = ['subscriptions', 'not like', '%'.$exclude.'%', 'and'];
            array_push($excludeQuery, $singleQuery);
        }

//        $included = Subscription::where($excludeQuery)->where($includeQuery)->get();
        $included = DB::table('subscriptions')
            ->join('app_users', 'app_users.customer_number', '=', 'subscriptions.customer_number')
            ->join('app_datas', 'app_datas.customer_number', '=', 'subscriptions.customer_number')
            ->where($includeQuery)
            ->where($excludeQuery)
            ->select('app_datas.device_token')
            ->get();
© www.soinside.com 2019 - 2024. All rights reserved.