/** * 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; }
/** * Paginate collection to match a num page * * @param int $neededNumPage - Needed page number * * @return Collection */ public function paginate($neededNumPage) { if ($this->_usePagination === false) { return $this; } // build the limit start $limitStart = max(0, $neededNumPage - 1) * $this->_paginationNbModelByPage; // limit fetch query for page $neededNumPage $this->_queryHelper->limit($limitStart, $this->_paginationNbModelByPage); return $this; }