3.6 创建、修改、保存记录

3.6.1 创建新记录

你可以使用fetchOne()从数据库中获取一条记录,但是你也要能够创建记录并保存它。使用fetchNew()方法就可以达到目的,该方法接受一个可选的数组参数来预先设置记录对象的属性。

<?php
// a new blog record with default values
$new_blog = $model->blogs->fetchNew();

// a new blog record with specified values
$new_blog = $model->blogs->fetchNew(array(
    'title' => 'New Title Text',
    'body'  => '(insert body here)',
));
[Warning]Warning

还有一个newRecord()方法,但是它通常是通过关系对象来建立已存在的记录对象或新记录对象。一般情况下,你不会用到这个方法。

3.6.2 修改一条记录

不管是对于一个新记录对象还是已存在的记录对象,你能够把它的属性单独列出来修改,也能够通过load()方法传递一个数据数组给它修改。

<?php
/**
 * @var Solar_Sql_Model_Record $item The result of fetchNew() or fetchOne(),
 * or a record from a collection.
 */

// modify the properties individually:
$item->title = 'Another Title';
$item->body  = 'Different body text';

// or modify them via load().
$data = array(
    'status' => 'draft',
    'title'  => 'Another Title',
    'body'   => 'Different body text',
);

$item->load($data);

// only load certain properties. useful for loading only
// specific values from a data source, e.g. $_POST.
$whitelist = array('title', 'body');
$item->load($data, $whitelist);

3.6.3 保存一条记录

一旦你已经修改一条记录,你可以使用save()方法更新或是插入这条记录。(记录对象知道它自己是否是新记录,如果是则插入数据库,如果不是则根据主键更新数据。)

[Note]Note

记录只会保存被修改过的数据;也就是“被弄脏了的”属性。

因为模型为记录定义了一些过滤器,如果任何一个验证失败,save()方法都将失败,所以你需要检查save()方法是否成功执行,如果没有的话,要查看哪里出错了。

<?php
/**
 * @var Solar_Sql_Model_Record $item The result of fetchNew() or fetchOne(),
 * or a record from a collection, and thereafter modified.
 */

// attempt to save the record.
$success = $item->save();

// did it work?
if (! $success) {
    // no, something was not valid
    $invalid = $item->getInvalid();
    foreach ($invalid as $property => $message) {
        echo htmlspecialchars($property) . ' is not valid: '
           . htmlspecialchars($message) . '<br />';
    }
    
    // or you can get the internal exception
    // that caused the save to fail.
    echo $item->getSaveException();
} else {
    // yes, it worked
    echo 'Saved!';
}

你可以把load()save()方法合并成save()方法,通过一个可选的“白名单”参数。

<?php
/**
 * @var Solar_Sql_Model_Record $item The result of fetchNew() or fetchOne(),
 * or a record from a collection.
 */

// incoming data
$data = array(
    'status' => 'draft',
    'title'  => 'Another Title',
    'body'   => 'Different body text',
);

// only load these properties
$whitelist = array('title', 'body');

// load and save the record in one call
$success = $item->save($data, $whitelist);

// did it work?
if (! $success) {
    // ...
} else {
    // yes, it worked
    echo 'Saved!';
}