PHP ActiveRecord,有许多自定义键

时间:2018-05-28 17:43:09

标签: php mysql activerecord phpactiverecord

我有以下表格架构(遗留系统,所以我无法改变它:-()

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_keyprimary_key列。 foreign_key更改了查询的where部分,primary_key不运行任何查询(仅SHOW COLUMNSusers上的admin_auths}。

TL; DR:如何在PHP ActiveRecord has_many关联上自定义连接?

0 个答案:

没有答案