Sprig_Core::create PHP Method

create() public method

Create a new record using the current data.
public create ( )
    public function create()
    {
        foreach ($this->_fields as $name => $field) {
            if ($field instanceof Sprig_Field_Timestamp and $field->auto_now_create) {
                // Set the value to the current timestamp
                $this->{$name} = time();
            }
        }
        // Check the all current data
        $data = $this->check($this->as_array());
        $values = $relations = array();
        foreach ($data as $name => $value) {
            $field = $this->_fields[$name];
            if ($field instanceof Sprig_Field_Auto or !$field->in_db) {
                if ($field instanceof Sprig_Field_ManyToMany) {
                    $relations[$name] = $value;
                }
                // Skip all auto-increment fields or where in_db is false
                continue;
            }
            // Change the field name to the column name
            $values[$field->column] = $field->_database_wrap($value);
        }
        list($id) = DB::insert($this->_table, array_keys($values))->values($values)->execute($this->_db);
        if (is_array($this->_primary_key)) {
            foreach ($this->_primary_key as $name) {
                if ($this->_fields[$name] instanceof Sprig_Field_Auto) {
                    // Set the auto-increment primary key to the insert id
                    $this->{$name} = $id;
                    // There can only be 1 auto-increment column per model
                    break;
                }
            }
        } elseif ($this->_fields[$this->_primary_key] instanceof Sprig_Field_Auto) {
            $this->{$this->_primary_key} = $id;
        }
        // Object is now loaded
        $this->state('loaded');
        if ($relations) {
            foreach ($relations as $name => $value) {
                $field = $this->_fields[$name];
                if (isset($field->foreign_key) and $field->foreign_key) {
                    $fk = $field->foreign_key;
                } else {
                    $fk = $this->fk($field->through);
                }
                $model = Sprig::factory($field->model);
                foreach ($value as $id) {
                    DB::insert($field->through, array($fk, $model->fk()))->values(array($this->_fields[$this->_primary_key]->_database_wrap($this->{$this->_primary_key}), $model->field($model->pk())->_database_wrap($id)))->execute($this->_db);
                }
            }
        }
        return $this;
    }

Usage Example

 /**
  * Overload the create method to auto-insert
  * the timestamp if one does not exist
  *
  * @return void
  * @author Sam de Freyssinet
  */
 public function create()
 {
     if (!isset($this->_fields['created'])) {
         return parent::create();
     }
     if ($this->created === NULL) {
         $this->created = time();
     }
     return parent::create();
 }