Home > Enterprise >  laravel DB::transaction how to update records?
laravel DB::transaction how to update records?

Time:11-11

I have a function in a controller like this:

DB::transaction(function () use ($request) {
            for ($parts=0; $parts < count($request->name) ; $parts  ) {
                $parts_info = new PartsInfo; 
                $parts_info -> part_id = $request -> id;
                $parts_info -> name = $request -> name[$parts];
                $parts_info -> qty = $request -> qty[$parts];
                $parts_info -> price = $request -> price[$parts];
                $parts_info -> save();
            }
        });

Now I want to update the records. How do I do that? Here multiple records have the same part_id which has a one-to-many relationship with another table. Note: Tried using $parts_info = PartsInfo::where('parts_id', $request->id)->get(); and without get()

CodePudding user response:

Try this one

  DB::transaction(function () use ($request) {
        for ($parts=0; $parts < count($request->parts) ; $parts  ) {
        
          PartsInfo::where("parts_id", $request->id)->update([
             "name" => $request->name[$parts],
              "qty" =>  $request->qty[$parts],
              "price" => $request->price[$parts]
            ]);

        }
    });

CodePudding user response:

try this one

 DB::transaction(function () use ($request) {
        for ($parts=0; $parts < count($request->parts) ; $parts  ) {
        
          PartsInfo::where('id', $request->id[$parts])->update([
             "name" => $request->name[$parts],
              "qty" =>  $request->qty[$parts],
              "price" => $request->price[$parts]
            ]);

        }
    });

You will have to check it with the id and because you are checking it with parts_id so it will not work

or You can first delete the child records and then recreate it

    DB::transaction(function () use ($request) {
        $count = $request->parts;
        PartsInfo::where('parts_id', $request->id)->delete();
        for ($parts=0; $parts < $count ; $parts  ) {
            PartsInfo::create([
                'parts_id' => $request->id,
                "name" => $request->name[$parts],
                "qty" =>  $request->qty[$parts],
                "price" => $request->price[$parts]                    
            ]);
        }
    });
  • Related