2011-10-03 35 views
2

我使用CakePHP CakePHP的過濾列表,這是我的數據庫的結構:由一決高下,而不是ID

 
CarMakes 
---------------------------------- 
ID  Slug  Name 
16  ford  Ford 

CarModels 
---------------------------------- 
ID  Name  CarMake_ID 
10  Escort 16 

Cars 
---------------------------------- 
ID  Name  CarModel_ID 
1  My car 10 

我想CarMakes.Slug

所以觀看汽車列表url將是: http://localhost/cars/ford

任何想法或信息的一般方向?

回答

4

您可以使用findBy()findAllBy()檢索基於ID以外的記錄。如果您需要提供的條件與查詢,使用常規find()

$this->Car->find(
    'all', 
    array(
     'conditions' => array(
     'CarMake.Slug' => $slug, 
     'Car.Name LIKE' => $name 
    ), 
    ) 
); 

此外,對於URL你想設置,你需要創建一個route/cars

Router::connect(
    '/cars/:make', 
    array('controller' => 'cars', 'action' => 'bymake'), 
    array(
     'pass' => array('make'), 
     'make' => '[A-Za-z]+' 
    ) 
); 

編輯:

上述工作,如果您的條件是基於您的模型的直接關聯。如果你的條件是一個遞歸關聯(即小車 - > CarModel-> CarMake),你需要使用明確連接:

$result = $this->Car->find('all', array(
    'joins' => array(
     array(
      'table' => 'car_models', 
      'type' => 'inner', 
      'foreignKey' => false, 
      'conditions' => array('car_models.id = Car.car_model_id') 
     ), 
     array(
      'table' => 'car_makes', 
      'type' => 'inner', 
      'foreignKey' => false, 
      'conditions' => array(
       'car_makes.id = car_models.car_make_id', 
       'car_makes.slug' => $slug 
      ) 
     ) 
    ), 
    'conditions' => array(
     'Car.name LIKE' => $name 
    ) 
)); 
+0

感謝這麼多的去努力編寫出了我,我會放棄一下。 – KieranYo

+0

我昨晚給了這個,我看到它現在正在做什麼,但我得到這個SQL錯誤: 'SQL錯誤:1054:未知列'CarMake.Slug'在'where子句'[CORE/cake/libs /model/datasources/dbo_source.php,第684行] – KieranYo

+0

您是否在模型中定義了Car和CarMake之間的關聯? –

相關問題