我正试图通过这些模型保存数据集。
模型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();
}
}
}
}
谢谢!
答案 0 :(得分:1)
我不得不通过另一个foreach循环来完成这项工作。是的,我觉得我正在迭代循环,所以如果有人有另一个优雅的解决方案,请务必将它们分享给我。 : - )
现在,已经完成了。
if (isset($_POST['Service'], $_POST['Response']))
{
// Assign and validate Service mcrypt_module_is_block_algorithm
$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);
// Assign and Validate Response Populated questions
foreach ($_POST['Response'] as $j => $k)
{
$response[$j] = new Response('populate'); // populate scenario
$response[$j]->attributes = $_POST['Response'][$j];
$valid = $response[$j]->validate() && $valid;
}
if ($valid)
{
foreach ($range as $key => $value)
{
$schedule = new Service; // static model
$schedule->attributes = $_POST['Service'];
$schedule->date_booked = $value->format('Y-m-d');
$schedule->save();
foreach ($_POST['Response'] as $x => $y)
{
$response[$x] = new Response('populate'); // populate scenario
$response[$x]->attributes = $_POST['Response'][$x];
$response[$x]->service_id = $schedule->id;
$response[$x]->save();
}
}
}
}