0
votes

How would I go about searching for a model across a related model? I have an author model and a post model. The author model has a "HAS_MANY" relation with posts and the post has a "BELONGS_TO" relation to an author. Essentially, each author has many posts. Given an author name and a post name, I need to get the post that fulfills this criteria. There will only be one match as the combination of author name and post name are unique. (this, I have working) The "author name" resides with the author model and the "post name" resides with the post model.

For non-relational models, I've been using this to find models:

ExampleModel::model()->findByAttributes(array('name' => $nameInput));

but I can't seem to figure out how to search across relations like I described above.

1

1 Answers

1
votes

Use a CDbCriteria instance and CActiveRecord::find() instead i.e

$c=new CDbCriteria

$c->together=true; 
$c->with=array('author'); //the name of the related model in the model you are searching

// the format for searching related fields is relation.field
$c->compare('author.name',$nameInput);
$c->compare('name',$postInput);

$post=Post::model()->find($c);