Relational Active Record

Hello, I have 3 tables: yii_posts, yii_category and yii_posts_category. They’re defined as follow:




CREATE TABLE IF NOT EXISTS yii_posts (

id bigint(20) unsigned NOT NULL AUTO_INCREMENT,

post_content longtext NOT NULL,

post_title text NOT NULL,

PRIMARY KEY (id)

);


CREATE TABLE IF NOT EXISTS yii_category (

id bigint(20) unsigned NOT NULL AUTO_INCREMENT,

category_name varchar(200) NOT NULL DEFAULT '',

category_slug varchar(200) NOT NULL DEFAULT '',

post_count bigint(20) NOT NULL DEFAULT '0',

PRIMARY KEY (id),

KEY category_slug (category_slug)

);


CREATE TABLE IF NOT EXISTS yii_posts_category (

post_id bigint(20) unsigned NOT NULL,

category_id bigint(20) unsigned NOT NULL,

PRIMARY KEY (post_id, category_id),

FOREIGN KEY(post_id) REFERENCES yii_posts (id),

FOREIGN KEY(category_id) REFERENCES yii_category (id)

);




And in the Posts Model, I defined the relations:




public function relations()

	{		

		return array(			

			'postCategory' => array(self::MANY_MANY, 'Category', '{{posts_category}}(post_id, category_id)'),

		);

	}



In the controller, I join try to join the tables using relational Active Record and print it out:


           

$criteria = new CDbCriteria;

$criteria->with = array('postCategory');

$criteria->together = true;

$posts =  Posts::model()->findAll($criteria);


CVarDumper::dump($posts[0]->category_name);




Howerver, It gives me this error:

I don’t know what went wrong. The relation is supposed to work as the examples in the RAC in yii wiki. Please help.

I figured out my problem. Turns out that Yii has returned the joined tables as an array of models under the name of relations. So, in order to access data in joined tables using rac:




$posts[0]->postCategory[0]->category_name;



To add WHERE condition using CDBCriteria:




$criteria->condition = "category_slug = :category_slug";

$criteria->params = array(':category_slug' => 'uncategorized');



Nice solution. :)

However, please call it postCategories, not postCategory. :)

You have many.

So you can do this without getting confused:




foreach($posts as $post) {

	foreach($postCategories as $postCategory) {

		echo $postCategory->stuff;

	}

}