2

在我的 ORM 模型中,我想保存一些基于其他值计算的默认值。我能想到的最好的是:

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

有谁知道是否有更好/推荐的方法来做到这一点,或者这对于大多数情况来说是否足够?谢谢 :)

4

2 回答 2

2

你的实现很好。您可以做的唯一改进就是将您的条件替换为:

if (!$this->_loaded) {
于 2010-11-22T06:00:21.653 回答
1

这是一个很好的问题。

不幸的是,你的方式只有可能。

在 ORM::create () 函数下方,从 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;
}

如您所见,没有默认值...

于 2014-12-08T08:55:08.637 回答