Basically, I want to build the relation between the tables ‘cities’ and ‘images’. They both have an ID column which is constrained by a third table called cities_images. Here’s the structure of the table in the middle:
CREATE TABLE IF NOT EXISTS `cities_images` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`cityId` int(11) NOT NULL,
`imageId` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `imageId` (`imageId`),
KEY `cities_images_ibfk_2` (`cityId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
ALTER TABLE `cities_images`
ADD CONSTRAINT `cities_images_ibfk_2` FOREIGN KEY (`cityId`) REFERENCES `cities` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `cities_images_ibfk_1` FOREIGN KEY (`imageId`) REFERENCES `images` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
I have two models that work with the cities and images tables.
Relation inside Cities.php:
'citiesImages' => array(self::MANY_MANY, 'CitiesImages', 'cities_images(id,cityId)'),
Relation inside Images.php:
'citiesImages' => array(self::MANY_MANY, 'CitiesImages', 'cities_images(id,imageId)'),
I am trying a test action inside CitiesController with the following content:
$cities = Cities::model()->findByPk(2);
var_dump($cities->images);exit;
But this results in an error:
Property “Cities.images” is not defined.
Note that there is a city with ID=2 and there is a row in cities_images with cityId=2 and imageId=1. There is also a row in the images table with ID=1, so I don’t see why I can’t access the images associated with the given City.
You are just referencing the wrong name. Should be:
Because that is how it is setup in the Cities.php model.
UPDATE:
Right, you need to simply change the models to point to the right model:
Cities.php:
Images.php: