简体   繁体   English

MongoDb,Yii2,活动记录:$或需要一个数组

[英]MongoDb, Yii2, Active Record: $or needs an array

everyone. 大家。

I have composed the following query in mongo and tested it using robomongo - it worked. 我已经在mongo中编写了以下查询,并使用robomongo对其进行了测试-它起作用了。

db.customers.find({$or: [
    {emailaddress: /.*test.*/},
    {address: /.*test.*/},
    {firstname: /.*test.*/}
]})

Now I am trying to implement this query in Yii2 using Active Record: 现在,我正在尝试使用Active Record在Yii2中实现此查询:

$fields = [];
$search = '/.*' . $search . '.*/';//in $search was the word 'test'

foreach($this->searchFields as $field) {
    $fields["$field"] = "$search";
}
$text_search = [ '$or' => ['$search' => $fields]];

$query = $query->where($text_search);

$provider = new ActiveDataProvider([
    'query' => $query,
]);

It worked before adding $or, and now it gives me an error: 在添加$ or之前它起作用了,现在却给了我一个错误:

"name": "MongoDB Exception",
"message": "Cannot run command count(): exception: $or needs an array",
"code": 20,
"type": "yii\\mongodb\\Exception",

Printing $test_search using print_r gives me: 使用print_r打印$ test_search给我:

Array
(
    [$or] => Array
    (
        [$search] => Array
        (
            [emailaddress] => : /.*test.*/
            [address] => : /.*test.*/
            [firstname] => : /.*test.*/
        )
    )
)

If I remove '$search' => and leave only 如果我删除'$search' =>并仅离开

$text_search = [ '$or' => [$fields]];

it gives me: 它给了我:

{
    "recordsTotal": 0,
    "recordsFiltered": 0,
    "data": []
}

Does anyone know how to make this query working in Active Record? 有谁知道如何使此查询在Active Record中运行? Please give me some ideas. 请给我一些想法。

Thanks in advance. 提前致谢。

You are missing that each "document" is meant to be a member of the $or array as it's own condition. 您会丢失每个“文档”本身就是$or数组的成员的信息。 You are making a single document with the different keys. 您正在使用不同的键制作单个文档。

Also you cannot use a regular expression from a "string" like that. 同样,您不能使用像这样的“字符串”中的正则表达式。 Rather use the $regex query operator, with just the string of the expression. 而是仅使用$regex的字符串使用$regex查询运算符。

Instead do: 而是:

$search = '.*' . $search . '.*';
$text_search = [ '$or' => [] ];

foreach($this->searchFields as $field) {
    array_push( $text_search['$or'], [ $field => [ '$regex' => "$search" ] ] );
}

$query = $query->where($text_search);

Also when you compare to JSON then output as JSON encoded for debugging purposes: 同样,当您与JSON比较时,然后输出为JSON编码以用于调试:

echo json_encode( $text_search, JSON_PRETTY_PRINT ) . "\n";

You can't go wrong then as you will see if it looks the same or not: 那么您不会出错,因为您会发现它看起来是否相同:

{
    "$or": [
        {
            "emailaddress": { "$regex": ".*test.*" }
        },
        {
            "address": { "$regex": ".*test.*" }
        },
        {
            "firstname": { "$regex": ".*test.*" }
        }
    ]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM