Esempio n. 1
0
 /**
  * 新增数据
  * @param Vo $vo
  * @param bool $fillPrikey
  * @return mixed|void
  * @throws \Simple\Model\Exception\DbException
  * @throws \Simple\Exception\UnexpectedValueException
  */
 public function add(Vo $vo, $fillPrikey = true)
 {
     if (!$vo instanceof PDOVo) {
         throw new UnexpectedValueException('vo参数必须为PDOVo对象。');
     }
     $tbName = $vo->getTableName();
     //表名称
     //数据库中的字段,不包括主键
     $fields = $vo->getFields(array($vo->getPrimaryKey()));
     $insertFields = array_map(function ($item) {
         return '`' . $item . '`';
     }, $fields);
     // 数据库对应的字段
     $binds = array_map(function ($item) {
         return ':' . $item . '';
     }, $fields);
     // bind的字段值
     $sql = 'INSERT INTO `' . $tbName . '` ( ' . implode(",", $insertFields) . ' ) values ( ' . implode(',', $binds) . ' );';
     $sth = $this->_link->prepare($sql);
     if (!$sth) {
         throw new DbException('error sql' . $sql . ',' . $sth->errorInfo());
     }
     foreach ($binds as $f) {
         $methodName = 'get' . lcfirst($f);
         $v = call_user_func_array(array(&$vo, $methodName), array());
         $sth->bindValue($f, $v);
     }
     try {
         $sth->execute();
     } catch (\PDOException $e) {
         throw new DbException($e->getMessage());
     }
     if ($fillPrikey == true && $vo->getPrimaryKey()) {
         //填充主键的值
         $pkMethod = "set" . ucfirst($vo->getPrimaryKey());
         $lastInsertId = $this->_link->lastInsertId();
         call_user_func_array(array(&$vo, $pkMethod), array($lastInsertId));
     }
 }