示例#1
0
文件: Model.php 项目: peacq/picorm
 /**
  * Insert model in database
  */
 private function insert()
 {
     // validate model PHP structure if necessary
     static::_validateModel();
     // create insert query for this model
     $queryHelp = new InternalQueryHelper();
     $queryHelp->insertInto(self::formatTableNameMySQL());
     // if primary key has forced value and is not present in tableField array
     if (!empty($this->{static::$_primaryKey}) && !in_array(static::$_primaryKey, static::$_tableFields)) {
         array_unshift(static::$_tableFields, static::$_primaryKey);
     } else {
         // use autoincrement for primary key
         $queryHelp->values(static::$_primaryKey, 'NULL');
     }
     // save model fields
     $params = array();
     foreach (static::$_tableFields as $unChamp) {
         // array is for raw SQL value
         if (is_array($this->{$unChamp}) && isset($this->{$unChamp}[0])) {
             $val = $this->{$unChamp}[0];
         } else {
             // mysql prepared value
             $val = '?';
             $params[] = $this->{$unChamp};
         }
         $queryHelp->values($unChamp, $val);
     }
     // execute insert query
     $query = static::$_dataSource->prepare($queryHelp->buildQuery());
     $query->execute($params);
     // check for mysql error
     $errorcode = $query->errorInfo();
     if ($errorcode[0] != "00000") {
         throw new Exception($errorcode[2]);
     }
     // model is saved, not new anymore
     $this->_isNew = false;
     // if empty PK grab the last insert ID for auto_increment fields
     if (empty($this->{static::$_primaryKey})) {
         $this->{static::$_primaryKey} = static::$_dataSource->lastInsertId();
     }
     return true;
 }
示例#2
0
 /**
  * Execute query and fetch models from database
  *
  * @return $this
  * @throws Exception
  */
 public function fetch()
 {
     $modelName = $this->_className;
     // execute fetch query
     $query = $this->_dataSource->prepare($this->_queryHelper->buildQuery());
     $query->execute($this->_queryHelper->getWhereParamsValues());
     // check for mysql error
     $errorcode = $query->errorInfo();
     if ($errorcode[0] != "00000") {
         throw new Exception($errorcode[2]);
     }
     // fetch query and hydrate models
     $fetch = $query->fetchAll(\PDO::FETCH_ASSOC);
     foreach ($fetch as &$unRes) {
         /** @var $object \PicORM\Model */
         $object = new $modelName();
         $object->hydrate($unRes, false);
         $unRes = $object;
     }
     // configure collection after fetch
     $this->isFetched = true;
     $this->models = $fetch;
     // if pagination used grab the total found model
     if ($this->_usePagination) {
         $this->_paginationFoundModels = $this->queryFoundModels();
     }
     return $this;
 }