基本上,我想建立表'城市'和'图像'之间的关系。它们都有一个ID列,该列受第三个名为cities_images的表约束。这是中间表格的结构:
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
我有两个适用于城市和图像表的模型。
Cities.php内的关系:
'citiesImages' => array(self::MANY_MANY, 'CitiesImages', 'cities_images(id,cityId)'),
Images.php内的关系:
'citiesImages' => array(self::MANY_MANY, 'CitiesImages', 'cities_images(id,imageId)'),
我正在CitiesController中尝试测试操作,其中包含以下内容:
$cities = Cities::model()->findByPk(2);
var_dump($cities->images);exit;
但这会导致错误:
未定义属性“Cities.images”。
请注意,有一个ID = 2的城市,cities_images中有一行,其中cityId = 2且imageId = 1。图像表中还有一行ID = 1,所以我不明白为什么我无法访问与给定城市相关的图像。
答案 0 :(得分:2)
您只是引用了错误的名称。应该是:
$cities = Cities::model()->findByPk(2);
var_dump($cities->citiesImages);exit;
因为这是在Cities.php模型中设置的方式。
更新:
是的,您只需将模型更改为指向正确的模型:
Cities.php:
'citiesImages' => array(self::MANY_MANY, 'Images', 'cities_images(imageId,cityId)'),
Images.php:
'citiesImages' => array(self::MANY_MANY, 'Cities', 'cities_images(cityId,imageId)'),