最近项目部分要迁移到mongodb上面去,因为之前是用Yii框架开发的,由于时间不够,不能立新项目只能在之前的项目中做更改,并且打算用YiiMongoDbSuite。
MongoDb原生不支持自增ID(Auto Increase ID)所以就自己做自增ID(当然这个方法也可以不用在框架实现)。
好了不说废话了,在组件中找到文件(EMongoDocument.php),然后任意地方加入代码:
public function getAutoincrementalId($autoSetMongoId = true)
{
if(is_array($primaryKey)) { $primaryKey = $primaryKey[0]; } // 如果是复合主键那么采用第一个就好了
$command = array(
'findAndModify' => 'autoIncreaseIds', // 这个名称也可以单独存出了来,这个就是主键集了
'update' => array('$inc' => array($this->primaryKey() => 1 )),
'query' => array('name' => $this->getCollectionName()),
'new' => true,
'upsert' => true
);
$res = $this->getDb()->command($command);
$autoIncreaseId = null;
if(isset($res['value'][$primaryKey])) {
$autoIncreaseId = $res['value'][$primaryKey];
if(false !== $autoSetMongoId) { $this->_id = $autoIncreaseId; } // 这里是我们的特殊需求了,需要将自增ID映射到_id,然后查询的时候再映射回来
}
return $autoIncreaseId;
}
从代码中可以看主要用的是findAndModify,这个东东类似于在MySQL中对于一场查询和update操作用事物,然后在后面的使用可以:
$model = User::model();
$autoIncreasedId = $model->getAutoIncreaseId();
var_dump($autoIncreasedId); // int(25)...
$model->id = $autoIncreasedId;
$model->username = 'tlq';
$model->createtime = time();
$model->save();
$userList = $model->findAll();
print_r($userList);
/*Array
(
[0] => User Object
(
[id] => 24
[username] => tlq
[_new:EMongoDocument:private] =>
[_criteria:EMongoDocument:private] =>
[_fsyncFlag:EMongoDocument:private] =>
[_safeFlag:EMongoDocument:private] =>
[useCursor:protected] =>
[ensureIndexes:protected] => 1
[_id] => 24
[_embedded:protected] =>
[_owner:protected] =>
[_errors:CModel:private] => Array
(
)
[_validators:CModel:private] =>
[_scenario:CModel:private] => update
[_e:CComponent:private] =>
[_m:CComponent:private] =>
)
[1] => User Object
(
[id] => 25
[username] => tlq
[_new:EMongoDocument:private] =>
[_criteria:EMongoDocument:private] =>
[_fsyncFlag:EMongoDocument:private] =>
[_safeFlag:EMongoDocument:private] =>
[useCursor:protected] =>
[ensureIndexes:protected] => 1
[_id] => 25
[_embedded:protected] =>
[_owner:protected] =>
[_errors:CModel:private] => Array
(
)
[_validators:CModel:private] =>
[_scenario:CModel:private] => update
[_e:CComponent:private] =>
[_m:CComponent:private] =>
)
)
*/
最后附上:
MongoDb的官方文档地址:http://docs.mongodb.org/manual/
YiiMongoDbSuite官方首页地址:http://www.yiiframework.com/extension/yiimongodbsuite