Easy Question: CActiveRecord relations

I have two tables: tbl_song and tbl_song_history. The song table has information about a song and song_history shows the dates of when a song was played with tbl_song_history.song_id as it’s FK to the tbl_song.id PK.

I would like to establish a relation so that I can retrieve the latest date of when a song was played. I’ve already been able to define a playCount relation:




public function relations() {    

   'playCount'=>array(self::STAT,'SongHistory','song_id'), 

}



How do I create one for the most recent date played?

The song_history table could contain zero or many entries for 1 song.

Much appreciated!

Patrick

BTW the two tables are:




tbl_song_history:

id int

song_id int

play_date timestamp






tbl_song

id int

title varchar(100)



Take a look at the relations section of the api. You can add some extra options in there to get the record of most recent play.




public function relations() {    

   'lastPlay'=>array(self::HAS_ONE,'SongHistory','song_id','limit'=>1,'order'=>'play_date'), 

}



That might get you the right thing. I don’t have anything exactly like this so I may be off a little. Of course, a solution like this will be getting you a SongHistory record, and not the exact value. What I mean is you’ll have to do this to get the value:




$lastPlay = $songModel->lastPlay->play_date;



Thanks for the response. I tried it and it appears you can’t use ‘limit’ with the HAS_ONE relation. I get this error:




Property "CHasOneRelation.limit" is not defined.