CActiveRecord and relations

Hi all,

I’ve never done any PHP coding before and Yii has been my first venture into it and MVC land.

There’s probably something I’ve missed here so any input would be great.

The tables are as follows:

Book(id, title, genre)

Genre(id, name)

Review(id, book_id, review)

Book.genre is a foreign key to Genre.id.

Review.book_id is a foreign key to Book.id.

I did all that in mysql and my relations() tells me exactly what I want.

I have used this statement and it returned what I need:




$rec = Book::model()->with('review', 'genre')->findByPk((int)$id);



$rec gives me:




[{"id":"1", "title":"PHP Cookbook", "genre":"1"}]



$rec->genre gives me:




[{"id":"1", "name":"Non-fiction"}]



$rec->comment gives me:




[

{"id":"1", "book_id":"1", "review":"Pure awesomeness"},

{"id":"2", "book_id":"1", "review":"Win++"}

]



I want to return that as JSON in one obj, at the moment I’m doing this:




$arr[] = $rec;

$arr[] = $rec->genre;

$arr[] = $rec->comments;

echo CJSON::Encode($rec);



It just seems wrong that I don’t have an object that embeds the genre and comments inside the book one.

Is that how it’s meant to be done and I’ll just handle it that way in the front end?

Thanks.

There is no such an object.

You can ovverride the getAttribute method of book for embed external values of relatad object:





	public function getAttributes()

	{

		return array_merge(parent::getAttributes(), array('genre'=>$this->genre->name), array('comments'=>$this->comment ));

	}