我有一个问题,当我使用来自mongoDB
的值时查询无法工作但在我尝试静态/硬编码值时有效。你能指出我做得不对吗?
当我硬编码如下所示的值时,代码工作正常。
$customer = $this->mongo->selectCollection('bookings');
$cursor = $customer->find(array('provider_id' => "0", 'cat_id' => array('$in' => array('591d380c227951b706e18a56','591da979227951a10f004ad7','591d42292279517209004ad7'))));
但是当值来自mongoDB时,此查询无法正常工作。
$cattype = array();
foreach ($catlist as $key => $value){ $cattype[] = "'".$value['cid']."'";}
$catlist = implode(',', $cattype);
$customer = $this->mongo->selectCollection('bookings');
$cursor = $customer->find(array('provider_id' => "0", 'cat_id' => array('$in' => array($catlist))));
$catlist = comes from mongoDB
提前致谢
有两个错误:
第一个是你的每一个。您可以添加'...'
,而不是添加ID。
foreach ($catlist as $key => $value){
$cattype[] = $value['cid']
}
第二个是在你的陈述中。你想传递$cattype
数组,但$cattype
已经是一个数组,所以你再次将它包装在一个数组中。
$cursor = $customer->find([
'provider_id' => "0",
'cat_id' => ['$in' => $catlist]
]);
请使用首先需要转换为mongo id,它可以帮助你。
$cattype = array();
foreach ($catlist as $key => $value) {
$cattype[] = new \MongoId($value['cid']);
}
$catlist = implode(',', $cattype);
$customer = $this->mongo->selectCollection('bookings');
$cursor = $customer->find(array('provider_id' => "0", 'cat_id' =>
array('$in' => array($catlist))));
$cattype = array();
foreach ($catlist as $key => $value) {
$cattype[] = $value['cid'];
}
$catlist = implode(',', $cattype);
$customer = $this->mongo->selectCollection('bookings');
$cursor = $customer->find(array('provider_id' => "0", 'cat_id' =>
array('$in' => $catlist))
);
我找到了答案。无需破坏$ cattype。只需将$ cattype直接放在$ in array中('$ in'=> array($ cattype))