如何在CakePHP模型中使用内连接

时间:2014-02-24 21:28:41

标签: cakephp join model associations model-associations

我有两张桌子,我想INNER JOIN,我花了好几个小时,但我没有运气。如果有人可以提供帮助,我会非常高兴。

我的第一张桌子:properties

id | room | price | location_id

我的第二张表是:locations

id | country | province | district

注意:location_id中的PropertiesLocation中是'id'

我想使用基本模型关联,例如hasOnebelongsTo等。

我应该在模型中加入什么才能基本上得到以下结果?

SELECT
    Property.room,
    Property.price,
    Location.province
FROM
    properties AS Property
INNER JOIN locations AS Location ON Property.location_id = Location.id

提前致谢!

5 个答案:

答案 0 :(得分:3)

以下模型关系将生成您需要的查询。

class Property extends AppModel {

    public $belongsTo = array(
        'Location' => array(
            'type' => 'INNER'
        )
    );

}

详细了解model associations

答案 1 :(得分:1)

使用以下代码:

$this->Property->find('all', array('joins' => array(array('table' => 'locations',
                                   'alias' => 'Location',
                                   'type' => 'INNER',
                                   'conditions' => array('Property.LOCATION_ID = Location.ID')))));

答案 2 :(得分:0)

试试这个

class Location extends AppModel {

    public $belongsTo = array('Property'));

}

class Property extends AppModel {

    public $hasOne = array( 'Location'));

}

答案 3 :(得分:0)

试试这个:

class Variant extends AppModel {

    $this->bindModel(array('belongsTo' => array('Brand' => array('type' => 'INNER'))));

}

答案 4 :(得分:0)

CakePHP支持定义自己的连接的语法。从PropertiesController

开始就可以这样做
$properties = $this->Property->find('all', array(
            'fields' => array('Property.*'),
            'joins' => array(
                array(
                        'table' => 'locations',
                        'alias' => 'Location',
                        'type' => 'INNER',
                        'conditions' => array(
                        'Property.location_id' =>'Location.id'
                        )
                    ),
                ),
            )
        );

您可以采取的另一种方式

您将与模型建立关系,并使用如下所示的可包含行为:

class Property extends AppModel {
    public $actsAs = array('Containable');
    public $belongsTo = array('Property');
}

class Location extends AppModel {
    public $actsAs = array('Containable');
    public $hasMany = array('Property');
}

然后您可以从PropertiesController

执行此操作
$properties = $this->Property->find('all', array(
    'contain' => array('Location')
));