开发者

CakePHP - How can I find all languages with tongue twisters?

Model

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

Controller

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

}
?>  

I only want 开发者_开发知识库to see languages on index() that have tongue twisters. How can I do this?


There might be a more efficient way, but here's how to pick only unique languages from the Tonguetwister table:

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

By the way, you don't need to put Language into $uses. Since they have a relation set you can access the Language model with $this->Tonguetwister->Language.


You don't really need to do two SQL queries for this. If the tables are joined on "language_alias" you can do something like this:

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

You should just do one query that's going to join the tables properly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜