Controller with Multiple Models

I’m looking through the Yii tutorials and can’t find any example of a controller that uses multiple models.

A good example is a Post controller that is able to show posts but with each post show all Topics related to it from the Topic model and all Comments for it from the comment model, etc etc.

I’m used to Grails and Cake other MVC frameworks that allow multiple models to be used in the controller. How does Yii allow this?

I’m not really sure I understand your question but if I understood it correctly what you’re asking for can be achieved in Yii with a relation.

If we assume that you have a Post model named ‘Post’, you could define your relations() as:


public function relations()


	return array(

		'comments' => array(self::HAS_MANY, 'Comment', 'postId'),




When you have your post model object you can easily access all comments posted under it as you can find your comments (assuming that they have been loaded with the model) by getting $post->comments. This will be an array of Comment model objects or a single Comment model object if only one is found for the particular post. It can of course also be empty if the post has no comments.

You can find out more about relations here:

Hope this helps. :)