Yii Framework Forum: Searching An Model's "has_Many' Relationship - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Searching An Model's "has_Many' Relationship Rate Topic: -----

#1 User is offline   jhonka 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 22
  • Joined: 22-June 12

Posted 01 March 2013 - 02:05 PM

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?
0

#2 User is online   softark 

  • Keep It Simple
  • Yii
  • Group: Moderators
  • Posts: 2,085
  • Joined: 16-February 11
  • Location:Japan

Posted 02 March 2013 - 01:47 AM

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.yiiframew...s_many-relation
0

#3 User is online   softark 

  • Keep It Simple
  • Yii
  • Group: Moderators
  • Posts: 2,085
  • Joined: 16-February 11
  • Location:Japan

Posted 02 March 2013 - 01:36 PM

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.yiiframew..._many-relation/
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users