-1

假设我有一个 Model_Post,它有_may Model_Comment。

每次保存新评论时,有什么方法updated_at可以更新 Model_Post 的字段?我检查了观察者的文档,但我找不到如何以“ORM 方式”进行操作。

此代码似乎不起作用:

class Model_Comment extends \Orm\Model
{
    protected static $_properties = array(
        'id',
        'post_id',
        'text',

    );
    protected static $_belongs_to = array('post');
    protected static $_observers  = array(
        'Orm\\Observer_UpdatedAt' => array(
            'events'          => array('before_save'),
            'relations'       => array('post')
        )
    );
}

class Model_Post extends Model
{

    protected static $_properties = array(
        'id',
        'title',
        'text',
        'updated_at'
    );
    protected static $_has_many   = array('comments');
}

我使用以下代码创建了一个新评论:

$comment             = Model_Comment::forge();
$comment->message_id = Input::post('message_id');
$comment->text       = Input::post('text');
$comment->save();
4

3 回答 3

1

如果您想要一个以 ORM 为中心的方法,而不是与观察者混在一起,您可以获取父对象,更新其 updated_at,然后通过 ORM 将两个对象提交到数据库。

但是,您没有实现整个观察者配置:。您缺少属性键和 mysql_timestamp 键。

// Adding it with config:
// - only needs to run on before_save
// - use mysql timestamp (uses UNIX timestamp by default)
// - use just "updated" instead of "updated_at"
protected static $_observers = array(
    'Orm\\Observer_UpdatedAt' => array(
        'events' => array('before_save'),
        'mysql_timestamp' => true,
        'property' => 'updated',
        'relations' => array(
            'my_relation',
        ),
    ),
);

FuelPHP Observer_UpdatedAt

于 2014-11-14T07:04:52.747 回答
1

如果您使用relations观察者配置的属性,您可以updated_at在关系更改时进行更新。只要您的子模型与父模型有关系,您就可以将关系名称添加到relations属性中,当您保存模型时,ORM 将为您完成剩下的工作。

请参阅文档中代码示例下的第一段。

于 2014-11-14T19:06:13.500 回答
0

多亏了Uru 的 评论,我终于找到了做到这一点的方法。

这段代码现在可以按我的意愿工作;它比我想象的要简单。

楷模:

class Model_Comment extends \Orm\Model
{
    protected static $_properties = array(
        'id',
        'post_id',
        'text',
    );
    protected static $_belongs_to = array('post');
}

class Model_Post extends \Orm\Model
{
    protected static $_properties = array(
        'id',
        'title',
        'text',
        'updated_at'
    );
    protected static $_has_many  = array('comments');
    protected static $_observers = array('Orm\Observer_UpdatedAt');
 }

在控制器中:

$comment       = Model_Comment::forge();
$comment->text = Input::post('text');
$parent_post   = Model_Message::find(Input::post('post_id'));

$parent_post->comments[] = $comment;
$parent_post->save();
于 2014-11-18T05:47:05.640 回答