2011-12-19 73 views
1

我这里有一个情况 有两种型号的用户,帖子 现在我想通过用户&帖子中调整的关系,或通过添加到列表发布的用户,其用户类型那些帖子= 1 这是可能的任何类型的范围?警予关系活动记录

我现在

User 
'Posts' => array(self::HAS_MANY, 'Post', 'userId'), 

Posts 
'User' => array(self::BELONGS_TO, 'User', 'userId'), 

回答

1

您可以命名范围或关系做到这一点。例如,你可以定义你的关系是这样的:

'Posts' => array(self::HAS_MANY, 'Post', 'userId', 'condition' => 't.userType=1') 

关于“命名范围”读到这里: http://www.yiiframework.com/doc/guide/1.1/en/database.ar#named-scopes

+0

不,这不是一个可行的解决方案。我认为这个关系需要调整 'User'=> array(self :: BELONGS_TO,'User','userId'), – iThink 2011-12-20 07:52:20

0

你想在这里做什么已经关系被称为关系的ActiveRecord查询。文档states

在关系AR查询时,别名为主表被固定 为t,而别名为一个关系表是相同的默认 对应关系的名称。例如,在以下 语句中,Post和Comment的别名分别为t和注释 。

所以,你需要做的是:

$posts = Posts::model()->findAll('user.userType = 1'); 
+0

感谢您的答复。但我想使用defaultScope或类似的东西,每次我查询帖子时,默认应用此搜索条件 – iThink 2011-12-19 15:32:23

1

您可以在飞行中添加的过滤器为命名范围调整的关系定义,像这样的:

class User extends CActiveRecord 
{ 
    public function relations() 
    { 
     return array(
      'Posts'=>array(self::HAS_MANY, 'Post', 'userId', 
       'with'=>array(
        'User'=>array(
         'scopes'=> array(
          'userType' => 1, 
         ), 
        ), 
       ), 
      ), 
     ); 
    } 
} 

更多信息可以在Yii的指南中找到为relational-query-with-named-scopes