代码之家  ›  专栏  ›  技术社区  ›  Teej

通过HABTM中的条件查找记录

  •  1
  • Teej  · 技术社区  · 14 年前

    我试图在一个类别内找到与一个类别相关联的帖子。现在,我有这个:

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

    但这似乎不起作用。显示以下内容时出错:

    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没有加入categories表。

    // 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'
            )
        );
    }
    
    3 回复  |  直到 14 年前
        1
  •  4
  •   Community leo1    7 年前

    我读过了,当你有了HABTM 在模特之间,你应该能够 像这样找回它。

    我不知道你在哪里读到的,但你的来源是错误的。 Cake's documentation of HABTM associations 处理一个与您的场景几乎相同的场景,以及实现您所追求的结果所需的步骤。

    My answer to another question about HABTM 可能有助于了解蛋糕的ORM是如何在封面下工作的。

        2
  •  0
  •   Teej    14 年前

    看来这起作用了。有没有更有效的方法来做到这一点?

    $options['joins'] = array(
        array('table' => 'categories_posts',
            'alias' => 'CategoriesPosts',
            'type' => 'LEFT',
            'conditions' => array(
                'Category.id = CategoriesPosts.category_id'
            )
        ),
        array('table' => 'posts',
            'alias' => 'Post',
            'type' => 'LEFT',
            'conditions' => array(
                'CategoriesPosts.post_id = Post.id',
            )
        )
    );
    $options['conditions'] = array(
        'Category.uri' => $uri
    );
    $options['fields'] = array(
        'DISTINCT(Category.uri), Post.*, Category.*'
    );
    $this->set('posts', $this->Category->find('all', $options));
    
        3
  •  0
  •   Teej    14 年前

    这是更有效的代码:

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