Welcome Guest, Not a member yet? Register   Sign In
php-activerecord and 2 foreign keys referring to one table
#3

[eluser]thevenin[/eluser]
sHiRoKKo1337 thank you for your contribution.

I found the answer on phpactiverecord official forum:

Code:
class Match extends ActiveRecord\Model {
  
    static $table_name = 'matches';

    static $belongs_to = array(
        array('home_team', 'class'=>'Team','foreign_key'=>'home_team_id'),
        array('away_team', 'class'=>'Team','foreign_key'=>'away_team_id')
    );
}

Code:
class Team extends ActiveRecord\Model {
    
    static $has_many = array(
        array('home_matches', 'class'=> 'Match'),
        array('away_matches', 'class'=> 'Match')
    );    
}

In the controller:

Code:
class Matches extends MY_Controller
{
    function index()
    {
        $this->output->enable_profiler(TRUE);
        $this->view_data['matches'] = Match::find('all');
    }
}

and finally in the index.php view:

Code:
<?foreach($matches as $match):?>
<li>&lt;?=$match->home_team->name?&gt; - &lt;?=$match->away_team->name?&gt;</li>
&lt;?endforeach?&gt;

Best regards.


Messages In This Thread
php-activerecord and 2 foreign keys referring to one table - by El Forum - 03-23-2012, 03:15 AM



Theme © iAndrew 2016 - Forum software by © MyBB