在 CakePHP 中获取多个插入的 hasMany 项目的 id
描述/说明:
在“添加活动”页面上,您可以添加多个时间表。当您 saveAll() 时,它会保存事件数据和所有时间表数据 - 这是正常工作的。
但是然后,我想处理时间表数据并在“日期”表中构建单独的行。
Event hasMany Schedule
Schedule belongsTo Event
Schedule hasMany Date
Date belongsTo 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。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是,$this->Event->Schedule->id仅保存插入的最后一个id。这就是为什么你总是得到相同的 id。
我想您正在事件控制器的添加功能中执行此 foreach 循环。
如果您想要每个自己的插入ID,您不应该对您的事件执行saveAll,而是循环遍历每个时间表(就像您已经做的那样)并将时间表保存在那里。这可能看起来像这样:
希望这有帮助!
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:
Hope this helps!