在 Laravel 中将 whereNot 与 elemMatch 与 mongo 一起使用

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

我有一个查询,用于根据用户个人资料过滤结果。我有一个应用于模型的国家/地区列表,并且仅显示 user.country 与该数组匹配的国家/地区。这部分对我来说效果很好:

... ->where(function ($q) {
       $q->whereNull('country')
         ->orWhere(
               'country',
               'elemMatch',
               ['country' => Auth::user()->country]
           );
          }
        )

现在我想添加“黑名单”功能,并且不向给定国家/地区列表中的用户显示某些内容,但它不起作用。

... ->where(function ($q) {
       $q->whereNull('country_exclude')
         ->orWhereNot(
               'country_exclude',
               'elemMatch',
               ['country' => Auth::user()->country]
           );
          }
        )

如何在 Laravel/Mongo 查询构建器中将

elemMatch
not
运算符一起使用?我有一条记录,我希望结果为
country_exclude:null
,但一旦我添加
orWhereNot
,它就会从结果中排除。

这是我正在查询的人口统计对象:

{
    "_id" : ObjectId("65e5a667792571b4d316fb75"),
    "country" : [ 
        {
            "country" : "A"
        }, 
        {
            "country" : "B"
        }
    ],
    "country_exclude" :  [ 
        {
            "country" : "C"
        }, 
        {
            "country" : "D"
        }
    ],
    ...
}
laravel-query-builder laravel-mongodb
1个回答
1
投票

用原始查询解决了这个问题:

...
->where(
   function ($q) {
       $q->whereNull('country_exclude')
           ->orWhereRaw(
               [
                   'country_exclude' => [
                      '$not' => [
                          '$elemMatch' => [
                              'country' => Auth::user()->country
                           ]
                       ]
                    ]
                ]
            );
   }
)...
© www.soinside.com 2019 - 2024. All rights reserved.