我設置了兩個模型:城市和國家。下面是我是如何定義他們: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(它不存在)進行關聯。另外,我是否正確地命名了我的類和表?謝謝
你有很多關係的國家和hasOne城市。簡單地刪除它們,那麼你只會得到citites。 –
工作,謝謝。但是,如果我想要去一個國家的城市,這些不是必需的嗎?我來自Rails,在你用類似的方式定義的Rails中,讓我們來做一些類似'cities = country.cities'的事情。那麼在CakePHP中定義hasOne和hasMany有什麼意義? – Martyn
$ belongsTo !!對不起,我打算用這個來代替$ hasOne。這就是我想要的關係。 – Martyn