提醒:本文最后更新于 2021-09-26 18:24,文中所关联的信息可能已发生改变,请知悉!
众所周知 Yii2 的 MongoDB 组件太老了 不支持新版本的事务操作和其他特性
现在当前文章来介绍一下 关于事务的开启和使用案例 (事务需要集群)
/**
* 开始事务
* @return \MongoDB\Driver\Session
* @throws Exception
*/ public static function startTransaction()
{if (is_null(static::getDb()->getDatabase()->connection->manager)) {static::getDb()->getDatabase()->connection->open();
if (is_null(static::getDb()->getDatabase()->connection->manager)) {throw new Exception('Please Connect Mongo');
}
}
$session = static::getDb()->getDatabase()->connection->manager->startSession();
$session->startTransaction([
'readConcern' => new \MongoDB\Driver\ReadConcern("snapshot"),
'writeConcern' => new \MongoDB\Driver\WriteConcern(\MongoDB\Driver\WriteConcern::MAJORITY),
]);
return $session;
}
案例:
$session = Order::startTransaction();
try {$model = new Order();
$result = $model->save(null,['session' => $session])
if (!$result) {throw new UserException('领取失败');
}
$session->commitTransaction();} catch (\Exception $e) {$session->abortTransaction();}
正文完