Change the search function based on related table

Consider these three tables with their relations:

Maker

[font=“Courier New”]‘analyzedObjects’ => array(self::HAS_MANY, ‘AnalyzedObject’, ‘maker_id’),[/font]

AnalyzedObject

[font=“Courier New”]‘imagings’ => array(self::HAS_MANY, ‘Imaging’, ‘object_id’),

‘maker’ => array(self::BELONGS_TO, ‘Maker’, ‘maker_id’),[/font]

Imaging

[font=“Courier New”]‘object’ => array(self::BELONGS_TO, ‘AnalyzedObject’, ‘object_id’),[/font]

Now, in the search form related to Imaging I would like to let the user search an imaging based on the maker. How should I modify the [font="Courier New"]search()[/font] function in [font="Courier New"]Imaging.php[/font] and the form in [font="Courier New"]_search.php[/font]?

Thank you!

Can’t you use


with

in your search depending on the field you are searching for? Basically joining the tables as you need them.

More info: http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#lazy-eager-loading

[color="#006400"]/* Moved from "2.0" to "1.1" */[/color]

Hi,

The following wiki article has been a "MUST READ" for Yii 1.1 development.

Searching and sorting by related model in CGridView (http://www.yiiframework.com/wiki/281/searching-and-sorting-by-related-model-in-cgridview)

You can not apply the wiki article just as is to your use case, but it surely will be a help.

  1. You have to declare a public property "maker_search" in your Imaging model.

  2. In the search() method of Imaging, you have to do it like the following:




$criteria = new CDbCriteria;

$criteria->with = array( 'object', 'object.maker' );

...

$criteria->compare( 'maker.name', $this->maker_search, true );



Thanks. The visualization and sorting work. Can you suggest me how to edit the advanced search form? This is where I’m starting from:




...

<div class="row">

		<?php echo $form->label($model,'maker_search'); ?>

		<?php echo $form->dropDownList($model,'maker_search',$this->getMakers(), array('prompt' => '--Select a maker--')); ?>

	</div>

...



Hi francesco,

Have you already implemented "getMakers()" method? And what does the item array (the return value of the method) look like?

I was thinking about a simple text input for "maker_search", because it is supposed to hold an arbitrary string for maker names.

If you want to use a dropdown for searching by the maker, you may consider using ‘maker_id’ instead of ‘maker_search’ in order to handle the id of the maker.

In "search()" method:




$criteria = new CDbCriteria;

$criteria->with = array( 'object', 'object.maker' );

...

$criteria->compare( 'maker.id', $this->maker_id );



In the view:




<?php

$options = CHtml::listData(Maker::model()->findAll(), 'id', 'name');

echo $form->dropDownList($model, 'maker_id', $options, array('prompt' => '--Select a maker--')); 

?>



Note that CHtml::listData() is a convenient method that you can use to construct the options array for a dropdownlist. Check it in the API.