2 relations away

Hi,

I’m new to OOP programming and programming with a framework. I’ve got a “best practice” type question:

I’m implementing the blog tutorial, but adding a “blog” table so there can be multiple blogs.

I’ve added a “last_activity” field to the blog table that I’d like to update with the current time whenever a post or a comment is saved.

So… in the post model, in the afterSave method, I’ve added this line, which works fine, because a particular instance of post has an “id_blog” attribute.


blog::model()->updateByPk($this->id_blog,array('last_activity'=>time()));

But, what’s the best way of implementing this in the comment model? There’s no id_blog attribute in the comment model, so I can’t do an updateByPk. I could do a SQL query joining on post to get id_blog, and then run the above code, but since so much seems to be “loaded” and “connected” in this framework, I’m wondering if there’s a better way, more “OOP/Framework” way to do this. How does the comment object know that, two relations away, it’s part of a blog - and does it have access to the id of that blog?

Thanks for your help.

-Charlie

hmm… no replies - so maybe just doing a query to get the id from the related post is the way to go? Or have I not explained this well.

You’ll have to read this: http://www.yiiframework.com/doc/guide/database.arr in order to understand how to use relations through the framework. After reading that, you could do something like the following:




// Relation in models/Post.php

'blog' => array(self::BELONGS_TO, 'Blog', 'blog_id'),


// Relation in models/Comment.php

'post' => array(self::BELONGS_TO, 'Post', 'post_id'),


// Create 2 blogs

$b1 = new Blog;

$b1->last_activity = 1000;

$b1->save();

$b2 = new Blog;

$b2->last_activity = 2000;

$b2->save();


// Create 1 post and update its blog last activity

$p = new Post;

$p->blog_id = $b1->id;

$p->save();


$p->blog->last_activity = time();

$p->blog->save();


// Create a comment for the above and update its blog last activity

$c = new Comment;

$c->post_id = $p->id;

$c->save();


$c->post->blog->last_activity = time();

$c->post->blog->save();