Thinkphph 使用RelationModel的三表关联查询机制

有如下三个表

a表 b表 c表
id bid other id cid other id other

a表的bid关联b表的id,b表的cid关联c表的id

现在需要查询a表的时候顺带把b表和c表的相关信息也查询出来

 

很多人一开始就想到使用原生的sql语句
select * from a left join b on a.bid=b.id left join c on b.cid=c.id;
但这并不是我想要的!

 

直接给出使用案例

class AModel extends RelationModel
{
    protected $_link = array(
        'B'=>array(
        'class_name' => 'B',
        'mapping_type' => self::BELONGS_TO,
        'mapping_name' => 'b',
        'foreign_key' => 'bid',//关联id
    ),
    //c表要间接关联b表
    'C' => array(
        'class_name' => 'C',
        'mapping_type' => self::MANY_TO_MANY,
        'mapping_name' => 'c',
        'mapping_key' => 'bid', // a.bid, a表要关联b表的字段
        'foreign_key' => 'id', // c.id 
        'relation_foreign_key' => 'cid', // b.cid b表要关联c表的字段
        'relation_table' => '__B__', //b表,双下划线加大写,会自动转换统一格式的表,如果多个大写例如BFModel,写成__B_F__中间需要用一个下划线隔开
    ),
);
    

  

posted @ 2018-03-26 17:52  Ariphan  阅读(452)  评论(0编辑  收藏  举报