Search code examples
cakephpcakephp-1.3has-manysaving-data

Getting the ids of multiple inserted hasMany items in CakePHP


Description / Explanation:

On the "Add an Event" page, you can add multiple Schedules. When you saveAll(), it saves the Event data and all the Schedule(s) data - this is working correctly.

But THEN, I want to process the schedule(s) data and build individual rows in the "dates" table.

Event hasMany Schedule
Schedule belongsTo Event
Schedule hasMany Date
Date belongsTo Schedule

So - I'm loading the Date model, and repeating through each Schedule that was passed, and processing/inserting the dates (based on repeat, start date...etc etc).

My problem / Question:

I need the id of each schedule for it's Dates ("schedule_id" field). How do I get the id's of individual Schedules during the repeat? Currently, I'm doing this:

foreach($this->data['Schedule'] as $i => $value) {
    $this->data['Date']['schedule_id'] = $this->Event->Schedule->id;
    //other stuff here
    $this->Date->saveAll($this->data['Date']);
}

But that gives me the same id in every loop.


Solution

  • The problem is, that $this->Event->Schedule->id only holds the LAST id of an insert. This is why you always get the same id.

    I suppose you are doing this foreach loop within your add-function of your Events-controller. If you want each own insert-id you shouldn't do a saveAll on your Event and rather loop through each Schedule (as you already do) and save the schedules there. This could look like this:

    foreach ($this->data['Schedule'] as $schedule) {
        $schedule['event_id'] = $this->Event->id; //this is needed because we don't do a saveAll on the Event anymore
        $this->Event->Schedule->save($schedule);
    
        //Here comes your part
        $this->data['Date']['schedule_id'] = $this->Event->Schedule->id;
        //other stuff here
        $this->Event->Schedule->Date->saveAll($this->data['Date']);
    }
    

    Hope this helps!