dongshicuo4844 2017-01-12 20:14
浏览 64

Laravel同步多个额外的动态值

I have a form where I submit multiple values. It's a dynamic form where the fields differ each time, but onlt the quantity of the fields, not the fields itself. I am using the following to insert all data in the pivot table, however I hardly think this is a good way of going about this. Is there a good way of accomplishing this without using a foreach perhaps? Right now for only 3 exercises I'm doing 12 queries? xD

The pivot table looks like this:

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
) 

And here is the code:

    $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]]);
    }
  • 写回答

1条回答 默认 最新

  • doushi5913 2017-03-11 16:46
    关注

    From laravel documentation

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

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题