I have the following table schema ( legacy system so I can't change it :-( )
admins:
admin_id
...
admin_auths:
admin_id ( connects to admin_id )
id ( connects to user_id )
auth ( only care about when this is 'user' )
...
users:
user_id ( connects to id )
...
Here is how I managed to get the relationship working for users:
User.php
class User extends ActiveRecord\Model {
static $has_many = [
[ 'admin_auths',
'foreign_key' => 'id', # key in linked table
'primary_key' => 'user_id', # key in "parent" (this) table
],
[ 'parents',
'through' => 'admin_auths',
'foreign_key' => 'id', # key in linked table
'primary_key' => 'user_id', # key in "parent" (this) table
'class_name' => 'Admin'
]
];
}
AdminAuth.php
class AdminAuth extends ActiveRecord\Model {
static $belongs_to = [
[ 'admin' ],
[ 'user',
'foreign_key' => 'id', # key in linked (this) table
'primary_key' => 'user_id', # key in "parent" table
]
];
}
If I call $user->parents or $user->admin_auths this works perfectly!
However I cannot seem to get it working in the Admin.php file:
class Admin extends ActiveRecord\Model implements JsonSerializable {
// relationships
static $has_many = [
[ 'admin_auths' ],
[ 'children',
'through' => 'admin_auths',
'class_name' => 'User'
]
];
...
}
The way it is shown above. This runs the following SQL:
SELECT `users`.* FROM `users` INNER JOIN `admin_auths` ON(`users`.user_id = `admin_auths`.user_id) WHERE `admin_id`=?
The problem with this is that I need to get it to join ON(`users`.user_id = `admin_auths`.id) ( there is no user_id column )
I've tried setting both the foreign_key and primary_key columns. foreign_key changes the where section of the query and primary_key runs no query ( Just SHOW COLUMNS on users and admin_auths ).
TL;DR: How to I customize the join on a PHP ActiveRecord has_many association?