Using variables in relation definitions

Hi folks,

I want to be able to use a variable in a relation definition. I think I am defining the relation correctly, but I do not know how to pass the value I want to this relation when I load it.

The relationship is defined as follows in the Keyword model:

public function relations()


  'recentcount'=>array(self::STAT, 'PostKeyword','kw_id',

                            'condition'=>'PostKeyword.p_id >= \':post_id\''),


basically I want to be able to find out how many times a keyword has been allocated to posts since a certain post id. How do I call this? Normally I know to use something like:

$stats = Keyword::model()->with('recentcount')->findAll();

I have tried:

$kwdata = Keyword::model()->with(array('recentcount'=>array('post_id'=>$post->id)))->findByPk($kw->kw_id);

but this does not seem to replace the variable in the query. The trace shows the query with the variable name in place, and the results reflect this - it shows a TOTAL count for that keyword, not just a count for that keyword since that post:

SELECT `kw_id` AS `c`, COUNT(*) AS `s` FROM `PostKeyword` WHERE (PostKeyword.p_id >= ':post_id') GROUP BY `kw_id` HAVING `PostKeyword`.`kw_id`=1232

If I then take that SQL and replace ‘:post_id’ with a real Post id, the query returns the desired result. This means my relationship is defined correctly, I just haven’t worked out the mechanism for getting that variable in there!

But how do I use a variable here? Sorry if this seems basic, but I have not run across this situation before.

Actually I figured it out without variables. I removed the condition from the relationship definition and put it in the with() call:

$kwdata = Keyword::model()->with(array('recentcount'=>array('condition'=>'PostKeyword.p_id >= '.$post->id)))->findByPk($kw->kw_id);

This will work too:

$kwdata = Keyword::model()->with(array('recentcount'=>array('params'=>array(':post_id'=>$post->id))))->findByPk($kw->kw_id);

Ah, thanks. That’s the perfect answer to the original question. I was just missing the extra $params array! now I know for next time :)

Can anything similar be applied to scopes? I would like to use a scope with a variable too.