可以包含条件

时间:2013-06-28 05:29:34

标签: cakephp cakephp-2.0 cakephp-2.1

我正在使用CakePHP可容纳。我试过的代码是......

 public function detail($slug = "") {
        $this->Poet->contain('User.id', 'User.full_name', 'Song.id', 'Song.name', 'Song.name_hindi', 'Song.slug');
        $result = $this->Poet->findBySlug($slug);
        if (!$result) {
            throw new NotFoundException(__('Invalid Poet - ' . $slug));
        }
        pr($result);
        die();
        $this->Poet->id = $result['Poet']['id'];
        $this->set('result', $result);
    }   

喜欢这个。现在我将Song.status作为我与Song table的关联。我想只获取那些status = 1的记录。可能吗?我可以用我的代码选择只有活动记录。

1 个答案:

答案 0 :(得分:2)

使用普通查找

虽然神奇的findBy *方法不时很方便,但最好只将它们用于琐碎的查询 - 你的查询不再是微不足道的。而是使用普通的查找呼叫,例如:

$result = $this->Poet->find('first', array(
    'contain' => array(
        'User' => array(
            'id', 
            'full_name'
        ),
        'Song' => array(
            'id', 
            'name',
            'name_hindi',
            'slug',
        )
    ),
    'conditions' => array(
        'slug' => $slug,
        'Song.status' => 1 // <-
    )
));

诗人有很多歌吗?

你没有在问题中提及你的关联,这对于提供准确的答案是相当重要的,但是诗人似乎有很多歌。考虑到这一点,第一个例子会产生一个sql错误,因为Poet和Song之间不会有连接。

可包含允许filtering associated data例如:

$result = $this->Poet->find('first', array(
    'contain' => array(
        'User' => array(
            'id', 
            'full_name'
        ),
        'Song' => array(
            'id', 
            'name',
            'name_hindi',
            'slug',
            'Song.status = 1' // <-
        )
    ),
    'conditions' => array(
        'slug' => $slug
    )
));

这将返回诗人(无论他们是否有相关歌曲),只返回状态为“1”的歌曲。您可以通过在association definition中定义条件(直接在模型中或使用bindModel)来实现完全相同的事情。

相关问题