模型关联(JOIN)在cakephp中不起作用,显示空结果

时间:2014-01-28 09:57:26

标签: mysql cakephp join model

我是cakephp的新手,目前正在开发一个版本为1.3的项目。基本上我试图显示插入数据库的提供者的城市名称。 我有两个模型:gal_store.phpgal_location.php。在gal_store模型中,商店名称与city表中的gal_stores字段中的相应城市ID一起保存。表格gal_locations包含所有城市及其名称。

所以我尝试按以下方式加入两个表:

var $hasOne = array(
        'GalLocation' => array(
            'className' => 'GalLocation',
            'foreignKey' => 'id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ),
    );

    function getList($limit = 50,$whether_list = false){
        $recursive = -1;
    $conditions = array("GalStore.city"=> "GalLocation.id");
        //$conditions = "";
    $order = array("GalStore.address");
        if($whether_list == true){
            return $this->find("list",array("DISTINCT GalStore.city","recursive"=>$recursive,"limit"=>$limit,"order"=>$order,"conditions" => $conditions));
        }else{
            return $this->find("all",array("DISTINCT GalStore.city","recursive"=>$recursive,"limit"=>$limit,"order"=>$order,"conditions" => $conditions));    
        }

    }

但在ctp文件中,当我执行var_dump($gal_locations);时,它始终显示为空!是什么原因?

1 个答案:

答案 0 :(得分:0)

如果gal_locations与gal_stores有一对一的关系,请使用以下代码:

var $hasOne = array(
    'GalLocation' => array(
        'className' => 'GalLocation',
        'foreignKey' => 'city',//if the city field contains the id of gal_locations table
        'conditions' => '',
        'fields' => '',
        'order' => ''
    ),
);

如果gal_locations与gal_stores有一对多的关系,请使用以下代码:

var $belongsTo = array(
    'GalLocation' => array(
        'className' => 'GalLocation',
        'foreignKey' => 'city',//if the city field contains the id of gal_locations table
        'conditions' => '',
        'fields' => '',
        'order' => ''
    ),
);