简体   繁体   English

Cakephp,使用find检索HABTM模型的数据

[英]Cakephp, Retrieve Data for HABTM Models using find

I am new to cakephp and I'm trying to accomplish something that should be relatively easy. 我是Cakephp的新手,我正在尝试完成一些相对容易的事情。 I have 2 models projects & categories bind by HABTM relationship. 我有2个模型项目和类别受HABTM关系约束。

I am trying to perform the following query -> find all projects that belong to a category 我正在尝试执行以下查询->查找属于某个类别的所有项目

$projects = $this->Project->find('all', array('conditions' => array('Category.slug' => $category)));

However when I'm doing so it generates an SQL error: 但是,当我这样做时会产生一个SQL错误:

SQL Error: 1054: Unknown column 'Category.slug' in 'where clause' 

What am I doing wrong? 我究竟做错了什么?

As far as I know,you can get what you want like this: 据我所知,您可以像这样得到:

/*in Project Controller file*/

$categorys = $this->Project->Category->find('all', array('conditions' => array('Category.slug' => $category)));

And you will probably get somethin as follows if set you HABTM relationship correctly: 如果正确设置HABTM关系,您可能会得到如下内容:

Array
(  
    [Category] => Array
    (
        [id] => xxx
        [name] => hello there
        ...
    )

    [Project] => Array
    (
        [0] => Array
            (
                [id] => 123
                [name] => Breakfast
            )
       [1] => Array
            (
                [id] => 124
                [name] => Dessert
            )
       [2] => Array
            (
                [id] => 125
                [name] => Heart Disease
            )
    )
)

It's what's you want,isn't it?See work with HABTM in cakephp in the cookbook. 这就是您想要的,不是吗?请参阅食谱中的cakephp中的HABTM使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM