Johhny P
Johhny P

Reputation: 161

Simple one to many relationship cakePHP

So there are to classes that have a relationship one to many. Event Type:

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

Event:

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

Previously the relationship was by the event_type_id, but now it was changed to initals. The problem occurs in the query when trying to access the data. At the end of the following query you can see that the left join is Event.event_type_initials = EventType.id, which doesnt make sense.

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

Any help is more than welcome.

Upvotes: 1

Views: 2263

Answers (1)

mark
mark

Reputation: 21743

If you specify a foreignKey it will always match to the id of the related table. You need to use conditions here, though:

// 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'
    )
); 

Upvotes: 3

Related Questions