2013-06-21 133 views
1

我有三個表:Yii的關係MANY_MANY:如何從關係表的屬性

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

User具有通過UserJoinEventEvent關係:

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

我想created時間user_join_event

回答

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; 
} 
+0

已記錄謝謝你的回答 – manhhaiphp