2010-03-11 5 views
4

내 프로젝트에서 메시지 검색을위한 작업을하고 있는데, 두 가지 모델이 있습니다 : Msgcontent와 Msgblock.Relationship은 Msgblock hasMany Msgcontent입니다. 내가하고 싶은 것은 ?cakephp에 hasMany 관계에 대한 조건을 찾았습니다.

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

그것은이 좋은 work.Is 더 나은 솔루션을 감사하지 보인다 다음과 같이 몇 가지 검색 keyword.My 코드 Msgcontent를 포함 Msgblock 기록합니다. ,

$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)) 
)); 

답변

8

조인,이 두 개의 쿼리와 함께 케이크에서 할 수있는 가장 쉬운 방법에 관한 것입니다

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

그리고 바인딩 할 때 이미 완료 되었기 때문에 조건없이 찾기를 사용할 수 있습니다.

+0

나는 이렇게 해냈고 Unknown column 'Msgcontent.content'in 'where clause'와 같은 오류를 일으킬 것이다. – Young

+0

@SpawnCxy 내 나쁜, 다른 방법은 (belongsTo) 작동합니다. – deceze

+0

@SpawnCxy 답변이 업데이트되었습니다. – deceze

1

당신은 조건 bindModel을 사용할 수 있습니다 예 : 적절한 사용하여 자신의 SQL 쿼리를 작성하는 짧은

-1

조건에서 하위 쿼리를 설정하여 hasMany 테이블을 검색하고 발견되는 경우 개수를 반환합니다. > 0

놀라 울 정도로 효과적이지 않지만 적절한 인덱싱이 용액은

(YOUR_HAS_MANY_TABLE.foreign_key = MAIN_TABLE.id YOUR_HAS_MANY_TABLE.field_to_search = '% 검색 %가'YOUR_HAS_MANY_TABLE에서 선택 카운트 (ID)) 그 일을 끝낼 수 있습니다.