繁体   English   中英

Laravel 查询用旧数据替换新数据

[英]Laravel query replace new data with old one

基本上这个问题是[链接]

由于这个问题太乱了,我想在这里分开这个问题。

解释

我在刀片中附加了行,其中将附加几个选择框,我可以选择每个选项。 此数据将保存在数据库中(直到这里一切都很好

问题

当我更改我选择的选项之一而不是更新时,它会将所有选择添加为新选项。

截图 1

一

代码

controller

public function spacssendto(Request $request) {
        $this->validate($request, array(
          'product_id' => 'required',
          'subspecifications' => 'required',
        ));

        // get all selected option
        $looped = $request->subspecifications;
        $spec = [];
        if(!empty($looped)){ //check if there is any select box without option
          foreach($looped as $sub) {
              $sub = Subspecification::find($sub);
              if (!empty($sub->id)) {
                  $data = (
                    [
                      'product_id' => $request->product_id,
                      'subspecification_id' => $sub->id,
                    ]
                  );
                  array_push($spec, $data);
              }
          }
      }
      dd($spec);
    //   DB::table('product_subspecification')->insert($spec); // save data to database
    }

截图 2

dd($spec)

二

任何的想法?

解决了

我已将我的功能更改为下面的代码,现在一切正常

public function spacssendto(Request $request) {
        $this->validate($request, array(
          'product_id' => 'required',
          'subspecifications' => 'required',
        ));
        $collection = collect($request->subspecifications)->map(function ($name) {
            return strtoupper($name);
        })
        ->reject(function ($name) {
            return empty($name);
        });
      $product = Product::find($request->product_id);
      $product->subspecifications()->sync($collection);
    }

希望它能帮助别人。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM