简单的一对多关系cakePHP

时间:2013-02-11 12:58:48

标签: cakephp cakephp-2.0 cakephp-2.1

因此,有一对多关系的类。 事件类型:

var $hasMany = array(
    'Event' => array(
        'className' => 'Event',
        'foreignKey' => 'event_type_initials',
        'dependent' => false,
    )
); 

事件:

var $belongsTo = array(
    'EventType' => array(
        'className' => 'EventType',
        'foreignKey' => 'event_type_initials'
    )
);

以前关系是event_type_id,但现在它已更改为初始化。尝试访问数据时,查询中出现问题。在以下查询结束时,您可以看到左连接是Eventevent_type_initials = EventTypeid,这没有任何意义。

SELECT `Event`.`id`, `Event`.`event_type_initials`, `Event`.`user_id`, `Event`.`details`, `Event`.`start`, `Event`.`hours`, `Event`.`minutes`, `Event`.`all_day`, `Event`.`active`, `Event`.`created`, `Event`.`modified`, `EventType`.`id`, `EventType`.`initials`, `EventType`.`name`, `EventType`.`address`, `EventType`.`email`, `EventType`.`phone`, `EventType`.`person`, `EventType`.`color` FROM `sunshine3`.`events` AS `Event` LEFT JOIN `sunshine3`.`event_types` AS `EventType` ON (**`Event`.`event_type_initials` = `EventType`.`id`**) WHERE `Event`.`id` = 30

任何帮助都非常受欢迎。

1 个答案:

答案 0 :(得分:3)

如果指定foreignKey,它将始终与相关表的id匹配。 但是你需要在这里使用条件:

// this is important for the correct left joins
var $belongsTo = array(
    'EventType' => array(
        'className' => 'EventType',
        'foreignKey' => false,
        'conditions' => array('Event.event_type_initials = EventType.initials')
    )
);

// for has many this is usually not necessary/possible (1:n), you can try though
var $hasMany = array(
    'Event' => array(
        'className' => 'Event',
        'foreignKey' => false,
        'conditions' => 'Event.event_type_initials = EventType.initials'
    )
);