ThinkPHP - 关联模型 - 多对多

时间:2022-02-11 09:16:50

表结构:
ThinkPHP - 关联模型 - 多对多

映射关系:

UserRelationModel会取UserRelation为表名称。所以要自定义表名称:

//定义主表名称
protected $tableName = 'User';

<?php
Class UserRelationModel extends RelationModel {
//定义主表名称
protected $tableName = 'User'; //定义关联模型
protected $_link = array(
'Role' => array(
'mapping_type' => MANY_TO_MANY,      //多对多关系
'foreign_key' => 'user_id',        //role对应的外键关系
'relation_foreign_key' => 'role_id',   //user表对应的外键关系
'relation_table' => 'ms_role_user',    //要关联的表
'mapping_fields' => 'id, name, remark' //关联哪些字段
)
);
}

查询的结果:

Array
(
[0] => Array
(
[id] => 1
[username] => admin
[logintime] => 1455336937
[loginip] => 127.0.0.1
[lock] => 0
[Role] => Array
(
) ) [1] => Array
(
[id] => 2
[username] => thinkbaitang
[logintime] => 1455339999
[loginip] => 127.0.0.1
[lock] => 0
[Role] => Array
(
[0] => Array
(
[id] => 1
[name] => Manager
[remark] => 普通管理员
) [1] => Array
(
[id] => 2
[name] => Admin
[remark] => 高级管理员
) ) ) [2] => Array
(
[id] => 3
[username] => zhangsna
[logintime] => 1455340000
[loginip] => 127.0.0.1
[lock] => 0
[Role] => Array
(
[0] => Array
(
[id] => 1
[name] => Manager
[remark] => 普通管理员
) [1] => Array
(
[id] => 2
[name] => Admin
[remark] => 高级管理员
) [2] => Array
(
[id] => 3
[name] => SuperAdmin
[remark] => 超级管理员
) ) ) )