Search field for the table with foreign key

Hello guys,

I’m new here and still learning yii.

I have a table studio




  `id` int(11) NOT NULL AUTO_INCREMENT,

  `name` varchar(100) NOT NULL,

  `city_id` int(5) NOT NULL,

  `descr` varchar(2600) DEFAULT NULL,

  `lng` decimal(14,10) DEFAULT NULL,

  `lat` decimal(14,10) DEFAULT NULL,

  `address` varchar(100) DEFAULT NULL,

  `tel` varchar(50) NOT NULL,

  PRIMARY KEY (`id`),

  KEY `fk_city_id` (`city_id`),

  CONSTRAINT `fk_city_id` FOREIGN KEY (`city_id`) REFERENCES `city` (`id`)

) 



city table contains 4 columns, but in this case only two are necessary


 id, name 

Using gii I created:


 public function relations()

  {

    return array(

      'city' => array(self::BELONGS_TO, 'City', 'city_id'),

    );

  }



On the Website I’d like to have a search field where I type the city name, press ‘submit’ button and get the studios in this city.

I have completely no idea how to do it in Yii. I will appreciate any help.

It’s not necessary to do it now, but then I’d like to use the results (studios in the city) to show them on the map using egmap.

Hi, jakub,

Probably this wiki will help you. This is a very good article, IMO.

Searching and sorting by related model in CGridView

こんにちは softark,

Thanks for your answer and the link to the article. The article allowed me to present the JOIN of two tables, but still the search field does not work. All studios are shown, and I can’t limit it by the city name.

edit: I’m on a good way to implement it :)

こんにちは jakub

It’s very nice to see a Japanese word. :)

In your case, you should have added a new attribute named something like ‘city_name_search’ to your Studio model, made it ‘safe’ on ‘search’, and modified the ‘search()’ function like …




$criteria = new CDbCriteria;

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

...

$criteria->compare('city.name', $this->city_name_search, true);

...



This should filter the search results by city name.