First, let assume there are two table: post and category. category is the master and post the details table.
// category table structure
CREATE TABLE `category` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 ;
// post table structure
CREATE TABLE `post` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`category_id` int(10) unsigned NOT NULL,
`user_id` int(10) unsigned NOT NULL,
`title` varchar(255) DEFAULT NULL,
`body` text NOT NULL,
`date_created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`date_updated` datetime DEFAULT NULL,
`is_visible` bit(1) NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_post_1` (`category_id`),
KEY `fk_post_2` (`user_id`),
CONSTRAINT `fk_post_2` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`),
CONSTRAINT `fk_post_1` FOREIGN KEY (`category_id`) REFERENCES `category` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
// Category model
class Category extends CActiveRecord
{
public function relations()
{
return array(
'posts' => array(self::HAS_MANY, 'Post', 'category_id'),
);
}
}
// Post model
class Post extends CActiveRecord
{
public function relations()
{
return array(
'category' => array(self::BELONGS_TO, 'Category', 'category_id'),
);
}
}
// Post controller
class PostController extends Controller
{
public function actionDisplay()
{
// if you want to set a condition to the post table
$models = Post::model()->with('category')
->findAll('is_visible = 1');
// if you want to set a condition to the category table
$models = Post::model()->with(array('category'=>array('condition'=>'id = 1')))
->findAll();
// if you want to set a condition to the category and post table together
$models = Post::model()->with(array('category'=>array('condition'=>'id = 1')))
->findAll('is_visible = 1');
$this->render('display', array('models'=>$models));
}
}
// view file (display.php)
<div class="xyz">
<?php
foreach($models as $model)
echo('Title: '.$model->title.'<br>Category: '.$model->category->name.'<hr>');
?>
</div>