Yii.Many_Many关系的条件


Yii. Condition on Many_Many relations

我有一个简单的结构:用户有帖子,帖子有标签。

如何获取所有标签,这些标签分配给给定用户的帖子?

我试着这样做:

$criteria = new CDbCriteria();
$criteria->together = true;
$criteria->with = array('posts');
$criteria->addSearchCondition('posts.user_id', $this->id);
//or this (by the way, what's the difference?):
//$criteria->compare('posts.user_id', $this->id);
$tags = Tag::model()->findAll($criteria);

但是它有问题。。这个条件给我标签,它只分配给这个用户的帖子。但我需要得到标签,它至少分配了这个用户的一个帖子。

换句话说,如果它是标记,它被分配了两个post:post1和post2(post1.user_id=1 post2.user_id=2),但我的用户id=1,那么这个标记就不会出现。但我想得到这个标签,因为它被分配了post1(post1.user_ud=1),我不关心其他帖子/用户。

如果我理解得对,您正在寻找一种方法来获取用户曾经使用过的所有标签。设置MANY_to_MANY rel的最简单方法是在模型关系中:

在您的用户模型中:

function relations()
{
    return array(
        'tags' => array(
            self::MANY_MANY,
            'Tag',
            'posts(user_id, tag_id)'
        ),
    );
}

然后使用您的模型,您就可以请求它们:

//gives you all the tags for user with PK 1
$usertags = User::model()->findByPK(1)->tags; 

参考:http://www.yiiframework.com/doc/guide/1.1/en/database.arr#declaring-关系

编辑:根据评论,我编辑了我的帖子,在活动记录上有更多的例子

$criteria=new CDbCriteria;
$criteria->with='tags'; 
$criteria->select='tag_name'; 
$criteria->condition='user=:userID';
$criteria->params=array(':userID'=>10);
$usertags =User::model()->findAll($criteria);