Nikolay Tuzov
Nikolay Tuzov

Reputation: 25

Yii. Condition on Many_Many relations

I have simple structure: Users have posts, posts have tags.

How can I get all tags, which assigned with posts of given user?

I tried do it this way:

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

But it has problems.. This condition give me tags, which assigned ONLY with posts of this user. But I need to get tags, which assigned at least with one post of this user.

In other words, if it is tag, which is assigned with two posts: post1 and post2 (post1.user_id=1 post2.user_id=2), but my user has id=1, then this tag wouldn't be in result. But I want get this tag, because it is assigned with post1 (post1.user_ud=1), and I don't care about other posts/users.

Upvotes: 1

Views: 463

Answers (1)

DarkMukke
DarkMukke

Reputation: 2489

If I understand this right, You are looking for a way to get all tags a user ever used. The easiest way to set up a MANY_to_MANY rel is in the model relations :

in your User model:

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

and then with your model you would just be able to request them :

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

Reference : http://www.yiiframework.com/doc/guide/1.1/en/database.arr#declaring-relationship

EDIT : Based on the comments I edit my post with more examples on Active Record

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

Upvotes: 1

Related Questions