【问题标题】:Getting the ids of multiple inserted hasMany items in CakePHP在 CakePHP 中获取多个插入的 hasMany 项的 id
【发布时间】:2011-05-10 21:27:32
【问题描述】:

描述/解释:

在“添加活动”页面上,您可以添加多个日程。当您 saveAll() 时,它会保存 Event 数据和所有 Schedule(s) 数据 - 这工作正常。

但是,我想处理时间表数据并在“日期”表中构建单独的行。

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

所以 - 我正在加载 Date 模型,并重复通过的每个 Schedule,并处理/插入日期(基于重复、开始日期等)。

我的问题/疑问:

我需要每个时间表的 ID 来表示它的日期(“schedule_id”字段)。我如何在重复期间获得各个时间表的 ID?目前,我正在这样做:

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']);
}

但这在每个循环中都给了我相同的 id。

【问题讨论】:

    标签: cakephp cakephp-1.3 has-many saving-data


    【解决方案1】:

    问题是,$this->Event->Schedule->id 只保存插入的 LAST id。这就是为什么你总是得到相同的 id。

    我想您是在事件控制器的 add-function 中执行此 foreach 循环。 如果您想要每个自己的 insert-id,则不应在 Event 上执行 saveAll ,而应遍历每个 Schedule (就像您已经做的那样)并将时间表保存在那里。这可能如下所示:

    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']);
    }
    

    希望这会有所帮助!

    【讨论】:

    • 确实有帮助,谢谢。唯一的问题是,它不会像 saveAll() 那样一起验证它们。有没有办法首先验证它们,然后进行这种类型的保存?非常感谢您的帮助!
    • 我相信我已经回答了我自己的问题 - 您可以手动验证 - 这里的信息:book.cakephp.org/view/1182/Validating-Data-from-the-Controller
    猜你喜欢
    • 2020-07-15
    • 1970-01-01
    • 1970-01-01
    • 2011-08-21
    • 2016-02-20
    • 2011-11-22
    • 1970-01-01
    • 2016-03-20
    • 1970-01-01
    相关资源
    最近更新 更多