Kohana 3 ORM - 如何判断当前保存的模型是否是新的?

时间:2010-11-22 05:56:40

标签: kohana kohana-3 kohana-orm

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

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

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

2 个答案:

答案 0 :(得分:2)

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

if (!$this->_loaded) {

答案 1 :(得分:1)

这是一个非常好的问题。

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

从ORM :: save()调用ORM :: create()函数。

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;
}

如你所见,没有defaut值......