【发布时间】:2013-10-11 20:47:32
【问题描述】:
好的,所以我有这个数组:
$ids = array(
"524f03c7a52c37a02100000f",
"574f03c7a52c37a02100002f",
"524f03c7a52c37a02100321f"
);
并且想要删除具有这些 id 的条目。我试过这个:
$carriers = Carriers::find([
"_id" => ["in" => $ids]
]);
还有这个:
$carriers = Carriers::find(["_id" => $ids]);
甚至这个:
$carriers = Carriers::findById($ids);
但它们似乎都不起作用。任何人都知道如何根据 ID 数组进行查找?
更新
这是用于删除的整个代码(根据@WiredPrairie 解决方案):
public function removeCarrierAction()
{
$request = new Phalcon\Http\Request();
if($request->isPost() == true){
if($request->isAjax() == true){
//get the string containing the uids and explode it into an array
$ids = explode(",",$request->getPost(0));
//do the query
$carriers = Carriers::find([['_id' => ['$in' => $ids]]]);
//delete with foreach
foreach($carriers as $carrier){
if($carrier->delete() == true){
echo "true";
}else{
echo "error";
}
}
}
}
}
当我打印count($carriers) 时,它会给出0。但是由于某种原因,上面的代码删除了集合中的所有条目。
更新(解决方案:)
问题很简单,当您在 MongoDB 中使用 id 时,您必须将其 id 转换为有效的MongoId() class。如果您只是将 uid 作为字符串传递,则它不起作用。你必须先转换它......所以我现在的代码是这样的:
public function removeCarrierAction()
{
$request = new Phalcon\Http\Request();
if($request->isPost() == true){
if($request->isAjax() == true){
//get and array of ids, and then apply MongoId() to each one of them
$ids = explode(",",$request->getPost(0));
$c = count($ids);
for($i=0;$i<$c;$i++){
$ids[$i] = new MongoId($ids[$i]);
}
//and then do the query
$carriers = Carriers::find([['_id' => ['$in' => $ids]]]);
//...
//do the delete loop here
}
}
}
就是这样。
这里有一个提示:使用 MongoDB 时,唯一不需要使用 MongoId() 转换 id 的情况是使用 ::findById(),否则,总是 使用MongoId() 转换您的ID。
【问题讨论】:
-
可能是
find(['_id' => ['$in' => $ids ]]),因为您正在尝试使用$in运算符。 -
它可以工作,但现在删除所有条目(由于某种原因,查询获取所有条目而不是过滤它)。即使将 $ids var 更改为“i-like-boobs”之类的字符串,它也会继续带来所有数据。
-
删除是什么意思?查找永不删除。
-
当然不是...但是当我使用
foreach()删除带有查找条目的$carriers时,它只会触发所有条目... -
这听起来像是一个不同的问题。查找
$in时返回了多少文档?