咱们来看看一个save方法用法。php
phalcon中的save方法,他是一个集 添加 和 修改 与一身的一个方法。git
$this->someModel->save($data);
在上面的这个方法中他会自动识别,在$data 数组中有没有 主键,github
if(主键存在){ 执行修改; }else{ 执行添加 }
可是咱们会发现,将$data 中没有的字段,他会清空。数组
下面由marser的phalconCMS中咱们能够看到,作了这样的处理app
/** * 封装phalcon model的update方法,实现仅更新数据变动字段,而非全部字段更新 * @param array|null $data * @param null $whiteList * @return bool */ public function iupdate(array $data=null, $whiteList=null){ if(count($data) > 0){ $attributes = $this -> getModelsMetaData() -> getAttributes($this); $this -> skipAttributesOnUpdate(array_diff($attributes, array_keys($data))); } return parent::update($data, $whiteList); }
其中getModelsMetaDatathis
/** * Returns the models meta-data service related to the entity instance * * @return \Phalcon\Mvc\Model\MetaDataInterface */ public function getModelsMetaData() {}
zephir源码code
/** * Returns the models meta-data service related to the entity instance */ public function getModelsMetaData() -> <MetaDataInterface> { var metaData, dependencyInjector; let metaData = this->_modelsMetaData; if typeof metaData != "object" { let dependencyInjector = <DiInterface> this->_dependencyInjector; /** * Obtain the models-metadata service from the DI */ let metaData = <MetaDataInterface> dependencyInjector->getShared("modelsMetadata"); if typeof metaData != "object" { throw new Exception("The injected service 'modelsMetadata' is not valid"); } /** * Update the models-metadata property */ let this->_modelsMetaData = metaData; } return metaData; }
和getAttributesip
/** * Returns table attributes names (fields) * * @param \Phalcon\Mvc\ModelInterface $model * @return array */ public function getAttributes(\Phalcon\Mvc\ModelInterface $model);
还有skipAttributesOnUpdateget
/** * Sets a list of attributes that must be skipped from the * generated UPDATE statement * <code> * <?php * class Robots extends \Phalcon\Mvc\Model * { * public function initialize() * { * $this->skipAttributesOnUpdate(array('modified_in')); * } * } * </code> * * @param array $attributes */ protected function skipAttributesOnUpdate(array $attributes) {}
zephir源码源码
/** * Sets a list of attributes that must be skipped from the * generated UPDATE statement * *<code> * <?php * * class Robots extends \Phalcon\Mvc\Model * { * public function initialize() * { * $this->skipAttributesOnUpdate( * [ * "modified_in", * ] * ); * } * } *</code> */ protected function skipAttributesOnUpdate(array! attributes) -> void { var keysAttributes, attribute; let keysAttributes = []; for attribute in attributes { let keysAttributes[attribute] = null; } this->getModelsMetaData()->setAutomaticUpdateAttributes(this, keysAttributes); }
都是phalcon自带的
用下面方式进行保存
$result = $this -> iupdate($data);
这样就将数据被清空的问题解决了。