在cakephp中执行简单查询

时间:2013-02-05 09:44:04

标签: cakephp has-many

电影有许多关系和关系属于电影。关系表有电影_id字段。 我想根据电影模型显示关系列表。所以在MoviesController.php我有:

public function view($id = null) {
    if (!$id) {
        $this->Session->setFlash(__('Invalid Movie', true));
        $this->redirect(array('action' => 'index'));
        }
    $this->set('Movie', $this->Movie->read(null, $id));
    $cid = $this->Movie->read('Relation.id');
    $cid_extract = Set::extract($cid, 'Relation.id');
    $this->set('planComps', $this->Movie->find('all',array('conditions' => array("movie_id" => $cid_extract))));
}

但我明白了

Error:  SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Relation.id' in 'field list'

SQL Query:  SELECT `Relation`.`id`, `Movie`.`id` FROM `myproject`.`movies` AS `Movie` WHERE `Movie`.`id` = 1 LIMIT 1

但我需要的查询是:

SELECT `Relation`.`id` FROM `myproject`.`relations` AS `relation` WHERE `Movie`.`id` = 1 LIMIT 1

我是cakephp的新手。请帮忙。

1 个答案:

答案 0 :(得分:1)

$this->loadModel('Relation');
$records = $this->Relation->find('all', array(
                'recursive' => -1,
                'conditions' => array('Relation.movie_id' => $movie_id),
                'fields' => array('Relation.id')
            ));