Yii Relation MANY_MANY:如何从关系表中获取属性

时间:2013-06-21 06:13:48

标签: yii relation

我有三张桌子:

CREATE TABLE `user` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(160) DEFAULT NULL,
  PRIMARY KEY (`id`)
)

CREATE TABLE `event` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
)

CREATE TABLE `user_join_event` (
  `user_id` int(10) unsigned NOT NULL,
  `event_id` int(10) unsigned NOT NULL,
  `created` datetime NOT NULL,
  PRIMARY KEY (`user_id`,`event_id`),
  CONSTRAINT `user_join_event_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`),
  CONSTRAINT `user_join_event_ibfk_2` FOREIGN KEY (`event_id`) REFERENCES `event` (`id`)
)

image

UserEvent的{​​{1}}有关系:

UserJoinEvent

我想在'events' => array(self::MANY_MANY, 'Event', 'user_join_event(user_id, event_id)'),

中获得created时间

1 个答案:

答案 0 :(得分:4)

您无法在具有many_many关系的连接表上获得其他属性,但您可以通过has_many关系执行此操作。不要忘记从表user_join_event

创建一个名为UserJoinEvent的模型

模型用户

'userJoinEvent' => array(self::HAS_MANY, 'UserJoinEvent', 'user_id'),
'events' => array(self::HAS_MANY, 'Event', 'event_id', 'through'=>'userJoinEvent'),

模型UserJoinEvent

'event' => array(self::BELONGS_TO, 'Event', 'event_id'),

Cotroller(示例获取事件的标题和使用pk 1从用户创建的日期)

$model = User::model()->findByPk(1);
foreach ($model->userJoinEvent as $item) {
  echo $item->event->title;
  echo $item->created;
}