[英]MongoDb, Yii2, Active Record: $or needs an array
大家。
我已經在mongo中編寫了以下查詢,並使用robomongo對其進行了測試-它起作用了。
db.customers.find({$or: [
{emailaddress: /.*test.*/},
{address: /.*test.*/},
{firstname: /.*test.*/}
]})
現在,我正在嘗試使用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,
]);
在添加$ or之前它起作用了,現在卻給了我一個錯誤:
"name": "MongoDB Exception",
"message": "Cannot run command count(): exception: $or needs an array",
"code": 20,
"type": "yii\\mongodb\\Exception",
使用print_r打印$ test_search給我:
Array
(
[$or] => Array
(
[$search] => Array
(
[emailaddress] => : /.*test.*/
[address] => : /.*test.*/
[firstname] => : /.*test.*/
)
)
)
如果我刪除'$search' =>
並僅離開
$text_search = [ '$or' => [$fields]];
它給了我:
{
"recordsTotal": 0,
"recordsFiltered": 0,
"data": []
}
有誰知道如何使此查詢在Active Record中運行? 請給我一些想法。
提前致謝。
您會丟失每個“文檔”本身就是$or
數組的成員的信息。 您正在使用不同的鍵制作單個文檔。
同樣,您不能使用像這樣的“字符串”中的正則表達式。 而是僅使用$regex
的字符串使用$regex
查詢運算符。
而是:
$search = '.*' . $search . '.*';
$text_search = [ '$or' => [] ];
foreach($this->searchFields as $field) {
array_push( $text_search['$or'], [ $field => [ '$regex' => "$search" ] ] );
}
$query = $query->where($text_search);
同樣,當您與JSON比較時,然后輸出為JSON編碼以用於調試:
echo json_encode( $text_search, JSON_PRETTY_PRINT ) . "\n";
那么您不會出錯,因為您會發現它看起來是否相同:
{
"$or": [
{
"emailaddress": { "$regex": ".*test.*" }
},
{
"address": { "$regex": ".*test.*" }
},
{
"firstname": { "$regex": ".*test.*" }
}
]
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.