Pregunta

En mi modelo ORM, me gustaría salvar algunos valores por defecto que se calculan sobre la base de otros valores. Lo mejor que podía llegar a decir:

function save(){
    if( ! $this->loaded()){
        // Set values here
    }
    parent::save();
}

¿Alguien sabe si hay una manera mejor / recomendada de hacer esto, o si esto será suficiente para la mayoría de los casos? Gracias:)

¿Fue útil?

Solución

Su aplicación es buena. La única mejora que podría hacer es simplemente reemplazar su condición de:

if (!$this->_loaded) {

Otros consejos

El `s muy buena pregunta.

Unfortunnaly su camino sólo es posible.

A continuación ORM :: crear la función () wich llamó desde ORM :: save ().

public function create(Validation $validation = NULL)
{
  if ($this->_loaded)
    throw new Kohana_Exception('Cannot create :model model because it is already loaded.', array(':model' => $this->_object_name));

  // Require model validation before saving
  if ( ! $this->_valid OR $validation)
  {
    $this->check($validation);
  }

  $data = array();
  foreach ($this->_changed as $column)
  {
    // Generate list of column => values
    $data[$column] = $this->_object[$column];
  }

  if (is_array($this->_created_column))
  {
    // Fill the created column
    $column = $this->_created_column['column'];
    $format = $this->_created_column['format'];

    $data[$column] = $this->_object[$column] = ($format === TRUE) ? time() : date($format);
  }

  $result = DB::insert($this->_table_name)
  ->columns(array_keys($data))
  ->values(array_values($data))
  ->execute($this->_db);

  if ( ! array_key_exists($this->_primary_key, $data))
  {
    // Load the insert id as the primary key if it was left out
    $this->_object[$this->_primary_key] = $this->_primary_key_value = $result[0];
  }
  else
  {
    $this->_primary_key_value = $this->_object[$this->_primary_key];
  }

  // Object is now loaded and saved
  $this->_loaded = $this->_saved = TRUE;

  // All changes have been saved
  $this->_changed = array();
  $this->_original_values = $this->_object;

  return $this;
}

Como se puede ver, no hay valores défaut ...

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top