Has_Many Like A Has_One

Hello,

I have the following database tables (models):

USER

id

name

GAME

id

name

BET

id

user_id

game_id

value

date

I have a view where all games are listed, using:

$games = Game::model()->findAll()

Game have a HAS_MANY relation with Bet, so if I use:

foreach ($games as $game) {

$game->bets

}

The $game->bets will bring an array with all the bets for that game, is there a way to get the Bet ActiveRecord or null for the current logged user using relations or the only way is to add a method in the Game model like:

public function getBetForUser($id) {

foreach ($this->bets as $bet) {


	if ($bet->user_id == $id)


		return $bet;


}


return null;

}

How many times the database will be accessed?

If I use $games = Game::model()->with(‘bets’)->findAll(), the database will be accessed only one time?

Thank you in advance.

Andre Delorme

Anyone?

You can declare another relation HAS_ONE with your custom conditions like:




'betUser' => array(self::HAS_ONE, 'Bet', 'game_id', 'condition'=>'your condition here',), 



With relations, you don’t need ‘with’, the declared relation is brough with the model:




$games = Game::model()->findAll()

you can access: $games->betUser->value;



Or… create an CActiveRecord or CDataActiveRecord as your needs like:




                $criteria=new CDbCriteria(array(

                    'condition'=>'user_id='.$this->id,

                ));                               

                $dataProvider=new CActiveDataProvider('Bet', array(

                    'criteria'=>$criteria,

                ));



Hope it helps