【问题标题】:How to use mongodb ObjectId value in where condition in yii2如何在yii2的where条件下使用mongodb ObjectId值
【发布时间】:2018-02-07 05:42:21
【问题描述】:

我必须在不同类型的角色中计算学生。

学生角色的 ObjectId 是 ObjectId("57ea5880b5ea6a0650005642")

public function count_allStudents() {
    $list = People::find()->select(['_id','roleid'])->where(['roleid'=>ObjectId("57ea5880b5ea6a0650005642")])->all();
    return count($list);
}

但它不检索。问题是ObjectId type
如何在where 中使用ObjectId

【问题讨论】:

  • 尝试添加转换(字符串) - 像这样:People::find()->select(['_id','roleid'])->where(['roleid'=> (string)new ObjectId("57ea5880b5ea6a0650005642")])->all()
  • 你可以用->count()代替->all()
  • ObjectId("57ea5880b5ea6a0650005642") - 这是函数,但它是错误的。对象由关键字newnew ObjectId("57ea5880b5ea6a0650005642")创建

标签: php mongodb yii2


【解决方案1】:

像这样使用它

public function count_allStudents() {
    $list = People::find()->select(['_id','roleid'])
                    ->where(['roleid'=> new MongoDB\BSON\ObjectId("$mongoId")])
                    ->all();
    return count($list);
}

使用MongoDB 命名空间。 http://php.net/manual/en/class.mongodb-bson-objectid.php

【讨论】:

  • 谢谢!如何定义$mongoId
  • 你可以使用你的id,这里是"57ea5880b5ea6a0650005642"
  • 不返回值。
  • 具有该 ID 的对象是否存在?
  • 是的,存在。还有其他替代解决方案吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-28
  • 2021-05-25
  • 1970-01-01
相关资源
最近更新 更多