改进Model类支持 按照查询条件 更新

This commit is contained in:
thinkphp
2016-05-05 12:34:39 +08:00
parent 0b22d6a970
commit b5beaeded3
2 changed files with 19 additions and 2 deletions

View File

@@ -64,6 +64,8 @@ abstract class Model implements \JsonSerializable, \ArrayAccess
protected $type = []; protected $type = [];
// 是否为更新数据 // 是否为更新数据
protected $isUpdate = false; protected $isUpdate = false;
// 更新条件
protected $updateWhere;
// 当前执行的关联对象 // 当前执行的关联对象
protected $relation; protected $relation;
@@ -287,6 +289,17 @@ abstract class Model implements \JsonSerializable, \ArrayAccess
} }
} }
if (empty($where) && !empty($this->updateWhere)) {
$where = $this->updateWhere;
}
if (!empty($where)) {
$pk = $this->getPk();
if (is_string($pk) && isset($data[$pk])) {
unset($data[$pk]);
}
}
$result = self::db()->where($where)->update($data); $result = self::db()->where($where)->update($data);
// 更新回调 // 更新回调
@@ -353,11 +366,15 @@ abstract class Model implements \JsonSerializable, \ArrayAccess
* 是否为更新数据 * 是否为更新数据
* @access public * @access public
* @param bool $update * @param bool $update
* @param mixed $where
* @return $this * @return $this
*/ */
public function isUpdate($update = true) public function isUpdate($update = true, $where = null)
{ {
$this->isUpdate = $update; $this->isUpdate = $update;
if (!empty($where)) {
$this->updateWhere = $where;
}
return $this; return $this;
} }

View File

@@ -1337,7 +1337,7 @@ class Query
if (!empty($options['model'])) { if (!empty($options['model'])) {
// 返回模型对象 // 返回模型对象
$data = new $options['model']($data); $data = new $options['model']($data);
$data->isUpdate(true); $data->isUpdate(true, $options['where']['AND']);
// 关联查询 // 关联查询
if (!empty($options['relation'])) { if (!empty($options['relation'])) {
$data->relationQuery($options['relation']); $data->relationQuery($options['relation']);