Let's say I have a Model_Post that has_may Model_Comment.
Is there any way that the updated_at
field of Model_Post gets updated every time that a new comment is saved? I checked the documentation for the observers, but I cannot find how to do that in a "ORM way".
This code doesn't seem to work:
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');
}
I create a new comment using this code:
$comment = Model_Comment::forge();
$comment->message_id = Input::post('message_id');
$comment->text = Input::post('text');
$comment->save();
Finally I found the way to do that thanks to Uru's comments.
This code works now as I wanted; it was simpler than I thought.
Models:
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');
}
And in the controller:
$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();