TIP: Use Markdown or, <pre> for multi line code blocks / <code> for inline code.
These forums are read-only and for archival purposes only!
Please join our new forums at discourse.kohanaframework.org
Relationship attributes and ORM
  • I'm making a website for managing an indoor football team (or indoor soccer, depending on where you live ;) ). For this I have 2 tables: "matches" and "players"

    They are related to eachother, because (obviously) players can play in matches. This is a many-to-many relation. So far, this is pretty simple for an ORM newbie like me :p. However, the relationship also has attributes. For example the position attribute. Every player has a position which can change each match (goalkeeper, regular player, coach, ..).

    My database looks something like this:

    matches match_id, home, visitor, home_score, visitor_score, date

    players player_id, user_id

    users user_id, name, ...

    matches_players match_id, player_id, position

    My code looks like this.

    <?php class Model_Match extends ORM { protected $_table_name = "matches"; protected $_primary_key = 'match_id'; protected $_has_many = array('players' => array('model' => 'player', 'through' => 'matches_players')); } class Model_Player extends ORM { protected $_table_name = "players"; protected $_primary_key = 'player_id'; protected $_has_many = array('matches' => array('model' => 'match', 'through' => 'matches_players')); protected $_has_one = array('user' => array('model' => 'user', 'foreign_key' => 'user_id')); } class Model_Match_Spelers extends ORM { protected $_table_name = "matches_players"; protected $_belongs_to = array('match' => array('model' => 'match', 'foreign_key' => 'match_id'), 'player' => array('model' => 'player', 'foreign_key' => 'player_id')) } ?>

    When I need info about a player, I can access it with:

    $match = ORM::factory("match", $matchID); $match->players->find_all() foreach($match->players AS $player){ echo $player->user->name; }

    Now my question is. How can I access the position attribute of the matches_players relation? Is there an easy way to do this through ORM?

  • Try sth like this (don't know it's working, but seems to be logically): $player->matches->where('match_id', '=', $matchID)->find()->position

  • After thinking this through a bit more, I think the main problem is my db design.

    I don't think I should see a player as a part of a many-to-many relation, but more as the many-side in a one-to-many relation and make it dependant on the match.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion