tags:

views:

369

answers:

1

Hi all,I'm working an action for message search in my project,and here are the two models:Msgcontent and Msgblock.Relationship is Msgblock hasMany Msgcontent.What I want to do is get all the Msgblock records that contain Msgcontent with some searching keyword.My code as follows:

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

It seems not a good work.Is there any better solution?Thanks.

+1  A: 

Short of writing your own SQL query with appropriate JOINs, this is about the easiest way to do it in Cake with two queries:

$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))
));
deceze
I had done it like that,and would cause an error like Unknown column 'Msgcontent.content' in 'where clause'
SpawnCxy
@SpawnCxy My bad, the other way around it would work (belongsTo).
deceze
@SpawnCxy Updated answer.
deceze
That's right.Thanks.
SpawnCxy