CakePHP 2 - 表的两个外键链接到同一个单表主键

时间:2017-07-21 12:55:52

标签: mysql cakephp cakephp-2.0 cakephp-2.9

我如何在这里使用cakephp 2X模型hasone或其他关联概念来执行查询查询。

My two tables

在我的Schinfo.php模型中是

class Schinfo extends AppModel {
    public $tablePrefix = 'sko_';
    public $hasOne = [
        'State' => [
            'className' => 'Masterlocation',
            'foreignKey' => 'master_locid'
        ],
        'City' => [
            'className' => 'Masterlocation',
            'foreignKey' => 'master_locid'
        ],
        'Area' => [
            'className' => 'Masterlocation',
            'foreignKey' => 'master_locid'
        ]
    ];
}

上面我得到了

SELECT
    `Schinfo`.`skool_id`,
    `Schinfo`.`skool_code`,
    `Schinfo`.`skool_name`,
    `Schinfo`.`skool_addr`,
    `Schinfo`.`master_state_id`,
    `Schinfo`.`master_city_id`,
    `Schinfo`.`master_area_id`,
    `Schinfo`.`skool_pin`,
    `Schinfo`.`skool_board`,
    `Schinfo`.`skool_type_id`,
    `Schinfo`.`skool_affilated_to`,
    `Schinfo`.`skool_affilated_no`,
    `Schinfo`.`skool_contact_no`,
    `Schinfo`.`skool_mailid`,
    `Schinfo`.`skool_website`,
    `Schinfo`.`skool_logo`,
    `Schinfo`.`skool_delete`,
    `State`.`master_locid`,
    `State`.`master_parentid`,
    `State`.`master_locname`,
    `State`.`is_checked`,
    `City`.`master_locid`,
    `City`.`master_parentid`,
    `City`.`master_locname`,
    `City`.`is_checked`,
    `Area`.`master_locid`,
    `Area`.`master_parentid`,
    `Area`.`master_locname`,
    `Area`.`is_checked` 
FROM
    `skoolata`.`sko_schinfos` AS `Schinfo` 
    LEFT JOIN
        `skoolata`.`sko_masterlocations` AS `State` 
        ON (`State`.`master_locid` = `Schinfo`.`id`) 
    LEFT JOIN
        `skoolata`.`sko_masterlocations` AS `City` 
        ON (`City`.`master_locid` = `Schinfo`.`id`) 
    LEFT JOIN
        `skoolata`.`sko_masterlocations` AS `Area` 
        ON (`Area`.`master_locid` = `Schinfo`.`id`) 
WHERE
    1 = 1

现在我需要改变

LEFT JOIN
    skoolata.sko_masterlocations AS State
    ON (State.master_locid = Schinfo.id) 
LEFT JOIN
    skoolata.sko_masterlocations AS City 
    ON (City.master_locid = Schinfo.id) 
LEFT JOIN
    skoolata.sko_masterlocations AS Area 
    ON (Area.master_locid = Schinfo.id)

LEFT JOIN
    skoolata.sko_masterlocations AS State
    ON (State.master_locid = Schinfo.master_state_id) 
LEFT JOIN
    skoolata.sko_masterlocations AS City 
    ON (City.master_locid = Schinfo.master_city_id) 
LEFT JOIN
    skoolata.sko_masterlocations AS Area 
    ON (Area.master_locid = Schinfo.master_area_id)

获得我的欲望输出

1 个答案:

答案 0 :(得分:0)

您希望定义三个关系CountryStateCity,并为每个关系指定className作为您要链接的模型,例如{{ 1}}。然后,您还可以使用Location指定要用作Student模型中的外键的列: -

foreignKey

然后,当找到结果时,您可以使用public $hasOne = [ 'Country' => [ 'className' => 'Location', 'foreignKey' => 'country_id' ], 'State' => [ 'className' => 'Location', 'foreignKey' => 'state_id' ], 'City' => [ 'className' => 'Location', 'foreignKey' => 'city_id' ] ]; ,如: -

contain