2011-08-02 64 views
0

型號CakePHP - 如何使用繞口令查找所有語言?

<?php 
class Tonguetwister extends AppModel { 
     var $name = 'Tonguetwister'; 
     //The Associations below have been created with all possible keys, those that are not needed can be removed 

     var $belongsTo = array(
       'language' => array(
         'className' => 'language', 
         'foreignKey' => 'language_alias', 
         'dependent'=> true 
       ) 
     ); 
} 
?> 

控制器

<?php 
class TonguetwistersController extends AppController { 

     var $name = 'Tonguetwisters'; 
     var $uses = array('Tonguetwister', 'Language'); 

     function index() { 
       $this->set('languages', $this->Language->find('all')); 
     } 

     function view($id = null) { 
       if (!$id) { 
         $this->Session->setFlash(__('Invalid tonguetwister', true)); 
         $this->redirect(array('action' => 'index')); 
       } 
       $this->set('tonguetwisters', $this->Tonguetwister->find('all', array('conditions' => array('language_alias' => $id)))); 
     } 

} 
?> 

我只希望看到指數語言()有繞口令。我怎樣才能做到這一點?

回答

2

有可能是一個更有效的方式,但在這裏是如何從Tonguetwister表只挑選獨特的語言:

function index() { 
    $languageList = $this->Tonguetwister->find( 
     'list', 
     array(
      'fields' => array('language_alias', 'language_alias'), 
      'group' => 'Tonguetwister.language_alias', 
      'recursive' => -1 
     ) 
    ); 

    // $languageList is now an array that holds the language ids 

    $this->set(
     'languages', 
     $this->Tonguetwister->Language->find(
      'all', 
      array( 
       'conditions' => array( 
        'Language.id' => $languageList 
       ) 
      ) 
     ) 
    ); 
} 

順便說一句,你不需要把語言變成$uses。由於他們有一個關係集,您可以通過$this->Tonguetwister->Language訪問語言模型。

+0

非常感謝!但是這給了我一個錯誤: 警告(512):SQL錯誤:1054:'where子句'中的未知列'Language.alias'[CORE/cake/libs/model/datasources/dbo_source.php,第684行]。表「languages.alias」與「tonguetwisters.language_alias」有關。 – Dennis

+0

要麼你把'language_alias'拼寫成'language.alias'或者關係定義有問題。 – JJJ

+0

是的,這是我模特中的一個資本錯字。謝謝!它完美的作品。 – Dennis

1

你並不需要爲此做兩個SQL查詢。如果表上的「language_alias」加入,你可以做這樣的事情:

function index() { 
    $this->Language->recursive = 0; 
    $this->set('languages', $this->Language->find('all', array(
     'conditions' => array($this->Language->alias.'.language_alias' => $this->Tonguetwister->alias.'.language_alias') 
    )); 
} 

你應該只是做一個查詢,那將正確地聯接表。