我有以下表格架构(遗留系统,所以我无法改变它:-()
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 )
...
以下是我如何设法让用户保持合作关系:
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
]
];
}
如果我致电$user->parents
或$user->admin_auths
,这完美无缺!
但是我似乎无法在Admin.php
文件中使用它:
class Admin extends ActiveRecord\Model implements JsonSerializable {
// relationships
static $has_many = [
[ 'admin_auths' ],
[ 'children',
'through' => 'admin_auths',
'class_name' => 'User'
]
];
...
}
上面显示的方式。这将运行以下SQL:
SELECT `users`.* FROM `users` INNER JOIN `admin_auths` ON(`users`.user_id = `admin_auths`.user_id) WHERE `admin_id`=?
这个问题是我需要让它加入ON(`users`.user_id = `admin_auths`.id)
(没有user_id列)
我已尝试同时设置foreign_key
和primary_key
列。 foreign_key
更改了查询的where部分,primary_key
不运行任何查询(仅SHOW COLUMNS
和users
上的admin_auths
}。
TL; DR:如何在PHP ActiveRecord has_many
关联上自定义连接?