我试图通过这些模型保存数据集。PHP:将foreach数据保存在foreach中
模型1:服务
生成一系列服务日期。
模型2:响应
对于每个服务的条目,用户需要增加的响应的定数。
所以,我想保存多个服务条目以获得多个响应。代码相当自我解释,但如果需要,我可以添加更多信息。我找不到一个简单的解决方案来做到这一点,尽管我觉得这很简单。
if (isset($_POST['Service'], $_POST['Response']))
{
$model->attributes = $_POST['Service'];
$valid = $model->validate();
// date manipulation
$start = new DateTime($model->date_booked);
$start->format('Y-m-d');
$end = new DateTime($model->end_date);
$end->format('Y-m-d');
$interval = DateInterval::createFromDateString($model->interval);
$range = new DatePeriod($start, $interval, $end);
if ($valid)
{
foreach ($range as $key => $value)
{
$schedule = new Service;
$schedule->attributes = $_POST['Service'];
$schedule->date_booked = $value->format('Y-m-d');
// If I were to save here, the following, Response Model
// will not be validated!
// $schedule->save();
foreach ($_POST['Response'] as $j => $k)
{
$response[$j] = new Response;
$response[$j]->attributes = $_POST['Response'][$j];
// If I were to save the Service Models here,
// evidently, entries are doubled up!
// $service->save();
$response[$j]->service_id = $service->id;
$valid = $response[$j]->validate() && $valid;
// $response[$j]->save();
}
}
}
}
谢谢!
首先你为什么使用嵌套的foreach?嵌套的foreach在php中存在问题。当你想要嵌套循环时,你的代码应该更好地使用for循环的基本结构。 – Greg
@Greg,我已经使用了foreach,因为我需要它来访问DatePeriod。请告知,如果你知道另一种方式。 – Glicious