【问题标题】:Laravel sync multiple additional dynamic valuesLaravel 同步多个额外的动态值
【发布时间】:2017-03-12 00:46:09
【问题描述】:

我有一个提交多个值的表单。它是一种动态形式,其中字段每次都不同,但只有字段的数量,而不是字段本身。我正在使用以下内容在数据透视表中插入所有数据,但是我几乎不认为这是解决此问题的好方法。有没有一种很好的方法可以在不使用 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]]);
    }

【问题讨论】:

    标签: php laravel laravel-5 synchronization pivot


    【解决方案1】:

    来自laravel documentation

    You may also pass additional intermediate table values with the IDs:
    
    $user->roles()->sync([1 => ['expires' => true], 2, 3]);
    

    【讨论】:

    • 谢谢,我已经尝试过了,但没有成功,但可能是我做错了。我有一段时间没有研究这个,我稍后会再检查一下:)
    猜你喜欢
    • 1970-01-01
    • 2015-05-08
    • 1970-01-01
    • 2021-01-13
    • 2015-12-24
    • 2017-07-16
    • 1970-01-01
    • 1970-01-01
    • 2013-11-14
    相关资源
    最近更新 更多