1
votes

I am fairly new to CakePHP, and am working on an event calendar. The events can be single day events or multiple days, so I created an events table and a dates table. When I save an event, the dates are saved in the Dates table as expected BUT the event_id field is always saved as 0 instead of the actual event id.

I think the relationships between the Events and Dates table is set properly.
This is what I have for the DatesTable:

    $this->table('dates');
    $this->displayField('id');
    $this->primaryKey('id');

    $this->addBehavior('Timestamp');

    $this->belongsTo('Events', [
        'foreignKey' => 'event_id'
    ]);

This is my EventsTable:

    $this->table('events');
    $this->primaryKey('id');

    $this->addBehavior('Timestamp');

    $this->belongsTo('Dates', [
        'foreignKey' => 'event_id',
        'joinType' => 'INNER'
    ]);

This is the code in my EventsController (WetKit is one of our plugins):

   $event = $this->Events->newEntity();

    if ($this->request->is('post')) {
        $event = $this->Events->patchEntity($event, $this->request->data, [
            'associated' => 'dates'
        ]);

        if ($this->Events->save($event)) {
            $this->Flash->success(__('The form has been saved.'));
        } else
            $this->WetKit->flashError(__('The form could not be saved because error(s) were found.'), $event);
    }

How can I get the event id to save in the Dates table?

1

1 Answers

0
votes

The association on the EventsTable side is wrong, it should be either a hasMany (1:n) association, or a hasOne (1:1) association. Given that you're talking about multiple days, I'd assume that you're looking for the former.

See also