Paul Carey Mon May 30 20:23:22 -0400 2011

Subject: Associations Through on Legacy DB

Hi

I am having some difficulty with setting up some associations on a legacy DB I have inherited.

Unfortunately the naming scheme for the DB is not consistant with the AR approach so this is where my woes start )-;*

The particular issue is with a Many to Many (:through) association..

The error I am getting is with the many to many join column being named incorrectly.

PHP-AR is generating a join like "INNER JOIN `userServiceTags` ON(`serviceTags`.id = `userServiceTags`.servicetag_id) "

Instead the userServiceTags`.servicetag_id should actually be userServiceTags`.serviceTagId

it looks a bit like this...

class User extends ActiveRecord\Model {
static $has_many = array(
array('user_service_tags', "foreign_key" => "userID"),
array('service_tags', "through" => "user_service_tags", "foreign_key" => "userID")
);
}
//This particular table actually has a composite key and no id column as primary but its not used as the joining table
class UserServiceTag extends ActiveRecord\Model {
static $table_name = 'userServiceTags';
static $belongs_to = array(
array('user',"foreign_key" => "userID", "primary_key"=>"id"),
array('service_tag',"foreign_key" => "serviceTagID", "primary_key"=>"id")
);
}
class ServiceTag extends ActiveRecord\Model  {
static $table_name = 'serviceTags';
static $has_many = array(
array('user_service_tags', "foreign_key" => "serviceTagID"),
array('users', "through" => "user_service_tags", "foreign_key" => "serviceTagID")
);
}

I'm certain is something stupid and obvious I am missing here, any help would be much appreciated.

Thanks.

P


Paul Carey Tue May 31 17:40:37 -0400 2011

I'm not entirelly sure I am correct on this but this is how I resolved the issue...

Afer putting my app under Xdebug for a while and stepping through the source for PHP-AR, I think there may be a slight issue with PHP-AR in such circumstances and I therefore decided to edit some code in the lib/Relationsip.php.

I have basically added a new option for has_many associations that allows the join_primary_key to be specified so that in such cases as above I can ensure it is set correctly.

This is probably a bit of a hackety hack to be fair but it works and I hope it helps someone else at some point.

I have branched and committed my changes, they can be viewed over at github
https://github.com/paulccarey/php-activerecord/commit/73801504a84e0576383388651dd14c53cf7dee62

With this change the User model now looks like this...

class User extends ActiveRecord\Model {
static $has_many = array(
array('user_service_tags', "foreign_key" => "userID"),
array('service_tags', "through" => "user_service_tags", "foreign_key" => "userID","join_primary_key" => "serviceTagId","class_name"=>"ServiceTag")
);
}

(1-1/1)