I am now discovering the Yii framework and doing it by trying to develop a simple application which allows to create Leagues and assign Players to it. The relationship between these is many to many (a player can subscribe to many leagues, and one league contains many players). So I have three db tables - tbl_league, tbl_player and tbl_league_player and I created foreign keys like this:
What I am trying to do here is to get all players from the Player table subscribed to a particular league ID. For this I have the Player model with relation defined like this:
public function relations()
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
'League' => array(self::MANY_MANY, 'League', 'tbl_league_player(player_id, league_id)'),
The problem is that I go to, for example, league/view&id=2, I am getting this error: "SELECT COUNT(*) FROM tbl_player t WHERE league_id=:leagueId" so it looks like the relation does not work. What am I missing?
I believe your criteria is stating to compare the league_id from the Player table. It won’t automatically do the join to the other table to perform the filtering. Take a look at the CDbCriteria::with property to make it join to other tables, although I’ve had problems doing this with stat queries in the past.
That said I would probably just load the League and use $league->players in the views.
Thanks for your help, guys. I was under the impression that models can handle relations via the third table, if not - whats the point specifying the MANY_MANY relation in the model?
Anyway - the main problem now is that if I use another way to obtain data - how would I display them? I was trying to use the [font="Courier New"]zii.widgets.CListView[/font] but, apparently, this only works with CActiveDataProvider, which I cant use because of the relation issue. Would you be able to help?