Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A find condition about hasMany relationship in cakephp

Tags:

cakephp

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.

like image 829
Young Avatar asked Feb 28 '23 10:02

Young


1 Answers

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))
));
like image 62
deceze Avatar answered Apr 06 '23 06:04

deceze