我有一个提交多个值的表单。它是一种动态形式,每次都有不同的字段,但是字段的数量,而不是字段本身。我使用以下内容在数据透视表中插入所有数据,但我不认为这是一个很好的方法来解决这个问题。也许有一种很好的方法可以在不使用foreach的情况下实现这一目标吗?现在只有3 exercises
我正在进行12次查询?的xD
数据透视表如下所示:
CREATE TABLE `exercise_training` (
`id` int(10) UNSIGNED NOT NULL,
`exercise_id` int(10) UNSIGNED NOT NULL,
`training_id` int(10) UNSIGNED NOT NULL,
`exercise_set` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`exercise_repeat` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`exercise_weight` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`exercise_time` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
)
以下是代码:
$checkedSets = $request['exercise_sets']; // Array of `set` values where the `key` is the `exercise_id`
$checkedRepeats = $request['exercise_repeats'];// Array of `repeat` values where the `key` is the `exercise_id`
$checkedWeights = $request['exercise_weights'];// Array of `weight` values where the `key` is the `exercise_id`
$checkedTimes = $request['exercise_times'];// Array of `time` values where the `key` is the `exercise_id`
foreach($checkedSets as $key => $value)
{
$training->exercises()->syncWithoutDetaching([$key => ['exercise_set' => $value]]);
}
foreach($checkedRepeats as $key => $value)
{
$training->exercises()->syncWithoutDetaching([$key => ['exercise_repeat' => $value]]);
}
foreach($checkedWeights as $key => $value)
{
$training->exercises()->syncWithoutDetaching([$key => ['exercise_weight' => $value]]);
}
foreach($checkedTimes as $key => $value)
{
$training->exercises()->syncWithoutDetaching([$key => ['exercise_time' => $value]]);
}
答案 0 :(得分:1)
You may also pass additional intermediate table values with the IDs:
$user->roles()->sync([1 => ['expires' => true], 2, 3]);