Domanda

Nel mio modello ORM, vorrei salvare alcuni valori di default, calcolati sulla base di altri valori. Il meglio che ho potuto venire in mente è:

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

Qualcuno sa se c'è una migliore / modo consigliato di fare questo, o questo dovrebbe essere sufficiente per la maggior parte dei casi? Grazie:)

È stato utile?

Soluzione

L'implementazione è buona. L'unico miglioramento che si potrebbe fare è solo sostituire il vostro condizione:

if (!$this->_loaded) {

Altri suggerimenti

`S molto bella domanda.

Unfortunnaly vostro senso solo possibile.

Di seguito ORM :: create function () wich chiamato da 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;
}

Come si può vedere, non ci sono valori il default ...

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top