![]() |
php-activerecord and 2 foreign keys referring to one table - Printable Version +- CodeIgniter Forums (https://forum.codeigniter.com) +-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20) +--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23) +--- Thread: php-activerecord and 2 foreign keys referring to one table (/showthread.php?tid=50290) |
php-activerecord and 2 foreign keys referring to one table - El Forum - 03-21-2012 [eluser]thevenin[/eluser] Hi. In php-activerecord it is easy to create association with foreign table when we're using standard field names ("user_id", "post_id", etc.) and there is only one FK associated with one foreign table: user_id -> users table, post_id -> posts table, etc. In my database I would like to retrieve teams' names for each match (table: matches). Every match record has 2 foreign keys: Code: home_team_id // referring to "teams.name" Code: away_team_id // referring to "teams.name" I know how to create query in plain SQL but I would like to use php-activerecord. Do you have any idea how to create delegates/associations to retrieve teams' names in $match object? "teams" table: Code: CREATE TABLE `teams` ( "matches" table: Code: CREATE TABLE `matches` ( php-activerecord and 2 foreign keys referring to one table - El Forum - 03-21-2012 [eluser]Akinzekeel[/eluser] I think you just need a JOIN. Also, you should use table aliases and field name aliases because you'll have to join the same table twice. Here's an example (untested): Code: $this->db->select( "m.id, ht.name home_team_name, at.name away_team_name" ); php-activerecord and 2 foreign keys referring to one table - El Forum - 03-23-2012 [eluser]thevenin[/eluser] sHiRoKKo1337 thank you for your contribution. I found the answer on phpactiverecord official forum: Code: class Match extends ActiveRecord\Model { Code: class Team extends ActiveRecord\Model { In the controller: Code: class Matches extends MY_Controller and finally in the index.php view: Code: <?foreach($matches as $match):?> Best regards. |