Hi, so giving yii a try in my new search for changing my framework of choice.
To start, i’ve decided to built something from scratch, so i started with a simple blog.
I have following tables (that matters in this converstation)
-> user (user_id pk)
-> post (post_id pk, user_id fk)
-> category (category_id pk)
-> post_to_category (post_id fk,category_id fk)
-> comment (comment_id pk, post_id fk)
Now, i have a url like /category/show/category-nice-url from where i check if that category exists and if so, i take the category_id to query for posts within that category .
I did like so :
//CategoryController
if( ! $category = Category::model()->find('url=:url',array(':url'=>$category_url)))
{
$this->render('category_error');
exit;
}
// get all the posts from category.
$posts = Post::model()->findAllBySql(
'SELECT p.*,u.* FROM post_to_category p2c
INNER JOIN post p ON p.post_id=p2c.post_id
INNER JOIN user u ON u.user_id=p.user_id
WHERE p2c.category_id=:category_id
ORDER BY p2c.post_id DESC',
array(':category_id'=>$category->category_id)
);
These are my defined relations :
//Category model
return array(
'parent' => array(self::BELONGS_TO, 'Category', 'parent_id'),
'categories' => array(self::HAS_MANY, 'Category', 'parent_id'),
'posts' => array(self::MANY_MANY, 'Post', 'post_to_category(category_id, post_id)'),
);
//Post model
return array(
'comments' => array(self::HAS_MANY, 'Comment', 'post_id'),
'user' => array(self::BELONGS_TO, 'User', 'user_id'),
'categories' => array(self::MANY_MANY, 'Category', 'post_to_category(post_id, category_id)'),
);
So, the question is, how to get the category posts using active records (maybe CDbCriteria) and further, how to get the post comments in same manner ?
Don’t get me wrong, i did searched the documentation, but i need a clear example .