私のORMモデルでは、他の値に基づいて計算されたいくつかのデフォルト値を保存したいと思います。私が思いつくことができる最高のものは次のとおりです。
function save(){
if( ! $this->loaded()){
// Set values here
}
parent::save();
}
これを行うためのより良い/推奨される方法があるかどうか誰かが知っていますか、それともほとんどの場合これで十分ですか?ありがとう :)
私のORMモデルでは、他の値に基づいて計算されたいくつかのデフォルト値を保存したいと思います。私が思いつくことができる最高のものは次のとおりです。
function save(){
if( ! $this->loaded()){
// Set values here
}
parent::save();
}
これを行うためのより良い/推奨される方法があるかどうか誰かが知っていますか、それともほとんどの場合これで十分ですか?ありがとう :)
あなたの実装は良いです。あなたができる唯一の改善はあなたの状態を次のように置き換えることです:
if (!$this->_loaded) {
とても良い質問です。
残念ながら、あなたのやり方は可能です。
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;
}
ご覧のとおり、デフォルト値はありません...