我希望你们可以帮助我:
首先要做的事情 - 我正在使用以下版本/库:
我正在尝试将我从数据库中获取的BSON阵列转换为在我的项目中使用。
据我所知,MongoDB中的一个很大的机会是在一个集合中拥有不同的有组织数据。 就像在这个例子中一样(只有一个对象具有“description”标签:
JSON文档:
{
enumbers ":[ {
"id": "84",
"enumber": "E 472 b",
"name": "Milchs\u00e4ureester von Mono- und Diglyceriden von Speisefetts\u00e4uren"
}, {
"id": "198",
"enumber": "E 407",
"name": "Carrageen",
"description": "Testdescription",
}, {
"id": "293",
"enumber": "E 941",
"name": "Stickstoff"
}]
}
我正在使用以下代码访问数据库:
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$collection = new MongoDB\Collection($manager, "test", "items");
$document = $collection->findOne(["id" => '5']);
$product= new Product($document);
直到这里工作正常。
use MongoDB\Model\BSONArray;
use MongoDB\Model\BSONDocument;
class Product
public function __construct(BSONDocument $data)
{
foreach ($data as $part){
try{
$this->setId($part->id);
$this->setEnumber($part->id);
$this->setName($part->name);
--------------------------------------
$this->setDescription($part->description);
--------------------------------------
}catch (\Exception $e){
echo $e;
}
}
echo "-------------------------------------------------".PHP_EOL;
}
现在是“$ this-> setDescription($ part-> description);”抛出异常:
ErrorException: Trying to get property of non-object
未定义“description”标签。
实际上我希望它在不存在的情况下返回null。
我如何正确地理解某些数据集可能有也可能没有这个标签?
希望你能帮助我和我感谢阅读:)
答案 0 :(得分:0)
我发现我试图在我的功能中访问“太深”的一层。 当我试图访问
时$this->setDescription($data->description);
我可以检查它是否已设置:
if (isset($data->name)) $this->setName($data->name);
的工作原理。
我以为我已经尝试过但没有结果 - 但我认为撰写应有论文会导致过度阅读。