本文介绍了通过HABTM中的条件查找记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试查找与类别关联的类别中的帖子。现在,我有这个:

I am trying to find posts within a category that are associated with a category. Right now, I have this:

$this->set('posts', $this->Category->Post->find('all', array('conditions' => array('Category.uri' => $uri))));

但这似乎行不通。错误显示如下:

But this doesn't seem to work. An error is showing this:

Warning (512): SQL Error: 1054: Unknown column 'Category.uri' in 'where clause' [CORE/cake/libs/model/datasources/dbo_source.php, line 684]

..<snipped>...

Query: SELECT `Post`.`id`, `Post`.`title`, `Post`.`uri`, `Post`.`body`, `Post`.`created`, `Post`.`modified` FROM `posts` AS `Post` WHERE `Category`.`uri` = 'holidays'.

我读到,当模型之间具有HABTM时,您应该能够像这样检索它。但是,显示的SQL不会加入类别表。

I've read that when you have HABTM between models, you should be able to retrieve it like so. However, the SQL shown doesn't JOIN the categories table.

// Category Model
class Category extends AppModel {
    var $name = 'Category';
    var $hasAndBelongsToMany = array(
        'Post' => array(
            'className' => 'Post'
        )
    );
}

// Post Model
class Post extends AppModel {
    var $name = 'Post';
    var $hasAndBelongsToMany = array(
        'Category' => array(
            'className' => 'Category'
        )
    );
}


推荐答案

这是效率更高的代码:

$this->set('posts', $this->Category->find(
    'first',
    array(
        'conditions' => array(
            'Category.uri' => $uri
        ),
        'contain' => array('Post')
    )
));

这篇关于通过HABTM中的条件查找记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 22:42