Searching An Model's "has_Many' Relationship

I am having problem doing searches with a has_many relationship.

I have a model called "Discussion." Each Discussion has many Comments. I am trying to create a search function so that a user can search any discussion in which a given string exists in ANY of the comments.

Something like below would be really nice:




public function search($division_id = null)

	{

		// Warning: Please modify the following code to remove attributes that

		// should not be searched.


		$criteria=new CDbCriteria;

                $criteria->with = array('comments');

                $criteria->compare('comment.text',$value,true);

                ...



It is pretty easy to do with a relationship where one model HAS ONE or BELONGS to another model but I am lost when it comes to HAS MANY.

Does anyone know how to do something like this? I have tried googling around and checking out this forum, but I haven’t found anything yet. Does such a feature exist?

Hi jhonka,

First, you may try this:




public function search($division_id = null)

	{

		$criteria=new CDbCriteria;

                $criteria->with = array('comments');

                $criteria->together = true; // maybe you will need this.

                $criteria->compare('comments.text',$value,true);  // not "comment" but "comments"

                ...



And, you may want to read this wiki article:

http://www.yiiframework.com/wiki/428/drills-search-by-a-has_many-relation

As a side note, I have just added a new chapter in the wiki.

I’m sure you all will like the update. Don’t miss it. :)

http://www.yiiframework.com/wiki/428/drills-search-by-a-has_many-relation/