Quantcast
Channel: Yii Framework Forum
Viewing all articles
Browse latest Browse all 18717

Has_Many Like A Has_One

$
0
0
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

Viewing all articles
Browse latest Browse all 18717

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>