2014-02-24 23 views
3

我有兩張表,我想INNER JOIN,我花了幾個小時,但我沒有運氣。如果有人能提供幫助,我會很高興。如何在CakePHP模型中使用內連接

我的第一個表:properties

id | room | price | location_id

我的第二個表是:locations

id | country | province | district

注:location_idProperties是 '身份證' 在Location

我想使用basi c模型關聯如hasOnebelongsTo等。

我應該在模型中放入什麼,以便基本得到以下結果?

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

在此先感謝!

+0

顯示您的模型定義 –

回答

3

以下模型關係會生成您需要的查詢。

class Property extends AppModel { 

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

} 

瞭解更多關於model associations

1

使用下面的代碼:

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

試試這個

class Location extends AppModel { 

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

} 

class Property extends AppModel { 

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

} 
0

試試這個:

class Variant extends AppModel { 

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

} 
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'); 
} 

然後你可以這樣做從01​​:

$properties = $this->Property->find('all', array(
    'contain' => array('Location') 
)); 
相關問題