gpt4 book ai didi

php - 将 MongoDB\Driver\Cursor 对象直接获取到指定类中

转载 作者:可可西里 更新时间:2023-11-01 10:41:42 25 4
gpt4 key购买 nike

目前,从 Mongo DB 中获取的每个文档都会转到一个 stdClass 对象。我想将它直接加载到我自己的自定义类中。

class TestClass {
private $id;
private $class;

function __construct($id, $name) {
$this->id = $id;
$this->class = $class;
}
}

代码

$m = MongoDB\Driver\Manager('mongodb://<user>:<pass>@<host>/<db>');
$query = MongoDB\Driver\Query(['name' => 'TestFirst']);
// I tried adding the following line, but it says that the constructor args are missing.
// If I omit it, it just adds each cursor object as an instance of stdClass
$opt = ['cursor' => new TestClass];

$results = $m->executeQuery('newDb.testCollection', $query, $opt);

foreach ($results as $document) {
var_dump($document);
}

我想要完成的是可能的,还是我需要遍历每个 stdClass 对象并将其转换为 TestClass 的实例?

最佳答案

类本身需要实现MongoDB\BSON\Unserializable接口(interface)和bsonUnserialize(array $data)方法将数组从BSON数据转换到类中问题。

class TestClass implements MongoDB\BSON\Unserializable, MongoDB\BSON\Serializable {
private $id;
private $name;

function __construct ($id, $name) {
$this->id = $id;
$this->name = $name;
}

function bsonUnserialize(array $data) {
// This will be called *instead* of the constructor if unserializing
$this->id = $data['_id'];
$this->id = $data['name'];
}
}

需要设置从查询返回的 MongoDB\Driver\Cursor 的类型映射,以将文档映射到自定义类的实例。完成的代码如下所示。

$mongo = new MongoDB\Driver\Manager($constr);
$query = MongoDB\Driver\Query(['name' => 'TestFirst']);
$cursor = $mongo->executeQuery($query);
$cursor->setTypeMap('root' => 'array', 'document' => 'TestClass', 'array' => 'array');

foreach ($cursor as $doc) {
var_dump($doc);
}

关于php - 将 MongoDB\Driver\Cursor 对象直接获取到指定类中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41516481/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com