I’ve got 2 simple tables:
message
id
subject
message_author_id
message_author
id
name
The relationship between the two tables is that one message_author can create multiple messages;
i.e., there’s a one-to-many relationship between message_author and message.
My goal is, when administering the message table, to be able to search on the messge_author.name field.
Here’s what I did, but searching by message author is turning up ALL messages in the message table:
// 1. Message model. Added new public property, messageAuthorFromName:
public $messageAuthorFromName;[
// 2. Message model. Added function afterFind(), so that the new property gets set when we search:
public function afterFind() {
$this->messageAuthorFromName = $this->message_author->from_name;
parent::afterFind();
return true;
}
// 3. Message model, relations function, generated by Gii:
[public function relations()
{
return array(
'message_author' => array(self::BELONGS_TO, 'MessageAuthor', 'message_author_id'),
);
}
// 4. Message model, rules() function
Added 'message_author' to the list of attributes that will be searchable by the user
// 5. Message model, attributeLabels() function. Added label:
'messageAuthorFromName' => 'Message Author',
// 6. Message model, search() function:
public function search()
{
$criteria=new CDbCriteria;
$criteria->with = array('message_author');
$criteria->addSearchCondition('message_author.from_name', $this->messageAuthorFromName, true);
return new CActiveDataProvider(get_class($this), array(criteria'=>$criteria));
}
// 7. Message view, _search.php includes a textfield for searching the messageAuthor:
[html] <div class="row">
<?php echo $form->label($model,'messageAuthorFromName'); ?>
<?php echo $form->textField($model,'messageAuthorFromName',array('size'=>60,'maxlength'=>255)); ?>
</div>[/html]
Can anyone spot what I’m missing? My hunch is that the search condition is being ignored.
I.e., in the code below, $this->messageAuthorFromName is BLANK, hence all results get returned:
public function search()
{
$criteria=new CDbCriteria;
$criteria->with = array('message_author');
$criteria->addSearchCondition('message_author.from_name', $this->messageAuthorFromName, true);
return new CActiveDataProvider(get_class($this), array(criteria'=>$criteria));
}
Any help appreciated!
Thanks!
Emily