Nicholas Morgan Mon Mar 19 12:19:59 -0400 2012

Subject: Simple (I think) association problem. Help!

I have a table called "games" and a table called "companies". The "games" table has fields called "publisher_id" and "developer_id" which are foreign keys that reference a company.

What syntax should I add into my models so that I can access the company information with something like $game->publisher->some_field_in_the_companies_table and $game->developer->some_field_in_the_companies_table?

Currently I have

class Game extends ActiveRecord\Model
{
    static $belongs_to = array(
        array('publisher', 'class_name' => 'Company'),
    );

}

But when I attempt something such as $game->publisher->company_name, I just get PHP errors. Help!


Max Schwanekamp Mon Mar 19 16:09:41 -0400 2012

You need to set the foreign_key property too. Something like this:

class Game extends ActiveRecord\Model
{
    static $belongs_to = array(
        array('publisher', 'class_name' => 'Company', 'foreign_key' => 'publisher_id'),
        array('developer', 'class_name' => 'Company', 'foreign_key' => 'developer_id'),
    );
}

I like to define the relationship both ways whenever possible, even though it's not necessary in the case you describe.

class Company extends ActiveRecord\Model
{
    static $has_many = array(
        array('published_games', 'class_name'=>'Game'),
        array('developed_games', 'class_name'=>'Game'),
    );
}

(1-1/1)