2012-06-12 3 views
1

다음 표 구조가 있습니다. tb_posts 내가 이름을 '갑'과 저자의 게시물의 검색을 수행하는 방법 내 게시물 YII를 사용하여 조인 된 테이블로 검색

public function relations() 
{ 

    return array(
     'authorRelation' => array(self::BELONGS_TO, 'authorRecord', 'author') 
    ); 
} 

액티브에서 나는 다음과 같은 한 YII에서 을 tb_author.id에 관한 필드 author_id이있다? 나는 성공하지 못한 채로 다음을 시도하고있다.

$criteria=new CDbCriteria; 
$criteria->with = array('authorRelation'); 
$criteria->together = true; 
$criteria->compare('author.name', 'foo', true); 
$posts=PostsRecord::model()->findAll($criteria); 

답변

1

init에서 모델에 대한 테이블 별칭을 설정한다. 마지막으로

class PostsRecord extends CActiveRecord 
{ 
    // ... 
    public function init() { $this->setTableAlias('postsrecord'); } 
    // ... 
} 

class AuthorRecord extends CActiveRecord 
{ 
    // ... 
    public function init() { $this->setTableAlias('authorrecord'); } 
    // ... 
} 

:

$condition=new CDbCriteria; 
$condition->with = array('authorRelation'); 
$condition->together = true; 
$condition->condition = 'authorrecord.name=:authorname'; 
$condition->params = array(':authorname' => 'foo'); 
$posts=PostsRecord::model()->findAll($condition); 
+0

실제로는 authorRelation을 사용하여 조건에서 이름이 트릭을했는데 나머지 코드는 제대로 작동하는 것 같았습니다. – FabioCosta

+0

'$ condition-> condition'을 '$ condition-> addSearchCondition'으로 대체해야합니다. ('author.name', 'foo', true);) –

+0

감사합니다. 차이점을보기 위해 문서를 살펴 보겠습니다. . – FabioCosta

1

귀하의 관계는 'authorRelation' => array(self::BELONGS_TO, 'authorRecord', author_id')해야한다. 세 번째 매개 변수는 외래 키입니다.

코드의 두 번째 부분에는 오류가 없으므로 관계를 올바르게 설정하면 검색이 작동합니다.

관련 문제