我想检查ArangoDB PHP是否已经存在Collection。
$collectionHandler = new CollectionHandler($arango);
$userCollection = new Collection();
$userCollection->setName('_profiles');
因为我得到以下错误:
Server error: 1207:cannot create collection: duplicate name cannot create collection: duplicate name
如何使用ArangoDB PHP检查集合是否已经存在?
我应该使用try/catch语句
try {
$collectionHandler = new CollectionHandler($arango);
$userCollection = new Collection();
$userCollection->setName('_profiles');
$collectionHandler->create($userCollection);
} catch (ServerException $e) {
// do something
}
使用异常处理来驱动程序流被认为是一种糟糕的风格——它应该用于真正的异常。在您的情况下,我认为包含用户配置文件的集合的先前存在是规则,而不是例外。
检查集合是否存在的正确方法是CollectionHandler::has($id)
。创建集合的正确方法是使用CollectionHandler::create($collection)
。create
接受一个字符串作为参数,即要创建的集合的名称。
$userCollectionName = '_profiles';
$collectionHandler = new CollectionHandler($arango);
$userCollection = $collectionHandler->has($userCollectionName) ?
$collectionHandler->get($userCollectionName)
:
$collectionHandler->create($userCollectionName);