2014-03-14 31 views
0

我設置了兩個模型:城市和國家。下面是我是如何定義他們:find('all')在CakePHP中執行意外的(不需要的)SQL連接

class City extends AppModel { // for "cities" table 
    public $hasOne = 'Country'; 
} 

class Country extends AppModel { // for "countries" table 
    public $hasMany = array(
     'City' => array(
      'className' => 'City' 
     ) 
    ); 
} 

,並在我的控制器:

public function getCities() { 
    $this->loadModel('City'); 
    $cities = $this->City->find('all'); 
} 

,但它給我這個錯誤:

Database Error 

Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Country.city_id' in 'on clause' 

SQL Query: SELECT `City`.`id`, `City`.`country_id`, `City`.`name`, `City`.`latitude`, `City`.`longitude`, `City`.`time_zone`, `City`.`dma_id`, `City`.`code`, `City`.`created`, `City`.`modified`, `Country`.`id`, `Country`.`country_id`, `Country`.`name`, `Country`.`code`, `Country`.`created`, `Country`.`modified` FROM `rtynbiz_ls`.`cities` AS `City` LEFT JOIN `rtynbiz_ls`.`countries` AS `Country` ON (`Country`.`city_id` = `City`.`id`) WHERE 1 = 1 

Notice: If you want to customize this error message, create app/View/Errors/pdo_error.ctp 

我不明白爲什麼它試圖與國家/地區表進行連接。我只想去城市。我如何阻止這種情況發生?而且,爲什麼它試圖使用Country.city_id(它不存在)進行關聯。另外,我是否正確地命名了我的類和表?謝謝

+0

你有很多關係的國家和hasOne城市。簡單地刪除它們,那麼你只會得到citites。 –

+0

工作,謝謝。但是,如果我想要去一個國家的城市,這些不是必需的嗎?我來自Rails,在你用類似的方式定義的Rails中,讓我們來做一些類似'cities = country.cities'的事情。那麼在CakePHP中定義hasOne和hasMany有什麼意義? – Martyn

+0

$ belongsTo !!對不起,我打算用這個來代替$ hasOne。這就是我想要的關係。 – Martyn

回答

0

下面的代碼行正在建立關係,所以JOIN存在。要刪除從查詢JOIN只需更換:

class City extends AppModel { // for "cities" table 
    public $hasOne = 'Country'; 
} 

class Country extends AppModel { // for "countries" table 
    public $hasMany = array(
     'City' => array(
      'className' => 'City' 
     ) 
    ); 
} 

有了:

class City extends AppModel { }// for "cities" table 

    class Country extends AppModel {} // for "countries" table 

您可以在表中的關係易於跟隨this

0

默認情況下,CakePHP會自動嘗試拉附加模型的數據。要停止從被默認在您的AppModel,設置此變量:

public $recursive = -1; 

我還建議增加中可容納的行爲,讓您的應用程序模型是這樣的:

<?php 
class AppModel extends Model { 
    public $actsAs = array('Containable'); 
    public $recursive = -1; 
} 

瞭解更多關於「遞歸「和」可容忍的行爲「在CakePHP book

0

如果不想做加盟當你想要檢索數據使其遞歸-1

public function get_cities() { 
    $this->loadModel('City'); 
    $this->City->recursive=-1; 
    $cities = $this->City->find('all'); 
    //or 
    $cities = $this->City->find('all', array('recursive'=>-1)); 
} 

任何方式,這將是你的模型:

class Country extends AppModel { 
    public $hasMany = array(
     'City' => array(
      'className' => 'City', 
      'foreignKey' => 'country_id', 
      'dependent' => false, 
     ), 
    ); 
} 

class City extends AppModel { 
    public $belongsTo = array(
     'Country' => array(
      'className' => 'Country', 
      'foreignKey' => 'country_id', 
     ) 
    ); 
} 

化妝確定你沒有在這兩個模型上的凌亂代碼