Question

Dans mon modèle ORM, je voudrais sauver quelques valeurs par défaut qui sont calculées en fonction d'autres valeurs. Le mieux que je pouvais trouver est:

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

Quelqu'un sait s'il y a une meilleure / façon de faire recommandé, ou si cela est suffisant pour la plupart des cas? Merci:)

Était-ce utile?

La solution

Votre mise en œuvre est bonne. La seule amélioration que vous pouvez faire est de remplacer simplement votre condition:

if (!$this->_loaded) {

Autres conseils

Il s `très bonne question.

Unfortunnaly votre chemin possible.

Ci-dessous ORM :: create () fonction Wich appelée à partir 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;
}

Comme vous pouvez le voir, il n'y a pas de valeurs ... defaut

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top