关于cakephp中hasMany关系的查找条件

时间:2010-03-11 03:33:07

标签: cakephp

我正在为我的项目中的消息搜索操作,这里有两个模型:Msgcontent和Msgblock.Relationship是Msgblock hasMany Msgcontent。我想要做的是获取所有包含Msgcontent的Msgblock记录和一些搜索keyword.My代码如下:

if($keyword)
{
    $conditions['and'] = array(
                                'Msgcontent.content LIKE'=>'%'.$keyword.'%',
                                'Msgcontent.content <>'=>''
                );
    $results = $this->Msgblock->Msgcontent->find('all',array('group'=>array('Msgblock.chatsessionid'),'conditions'=>$conditions));
}

这似乎不是一项好工作。有没有更好的解决方案?谢谢。

4 个答案:

答案 0 :(得分:8)

如果没有使用适当的JOIN编写自己的SQL查询,这是使用两个查询在Cake中执行此操作的最简单方法:

$ids = $this->Msgblock->Msgcontent->find('all', array(
    'fields' => array('Msgcontent.msgblock_id'),
    'recursive' => -1,
    'conditions' => ...
));

$this->Msgblock->find('all', array(
    'conditions' => array('Msgblock.id' => Set::extract('/Msgcontent/msgblock_id', $ids))
));

答案 1 :(得分:1)

您可以将bindModel与条件一起使用,例如:

$this->Msgblock->bindModel(
                   array(
                     'hasMany' => array(
                         'Msgcontent' => array(
                            'className' => 'Msgcontent',
                            'conditions' => array(
                                'Msgcontent.content LIKE' => "%$keyword%"
                            )
                         )
                     )
);

然后您可以无条件地使用您的查找,因为它已在绑定时完成。

答案 2 :(得分:0)

这是使用Cake的Containable行为的完美情况,如multidèria's excellent answer中对very similar question的讨论。将Containable添加到您的Msgcontent模型$actsAs,或者动态附加行为。

答案 3 :(得分:-1)

在条件中设置子查询,搜索hasMany表并返回计数(如果找到)。

(从YOUR_HAS_MANY_TABLE中选择计数(id),其中YOUR_HAS_MANY_TABLE.foreign_key = MAIN_TABLE.id,其中YOUR_HAS_MANY_TABLE.field_to_search ='%SEARCH%')&gt; 0

效率并不高,但通过适当的索引,它是一种可以完成工作的解决方案。

相关问题