cakephp save drag and drop list order to database



PHP Snippet 1:

UIkit.util.on(".uk-sortable", "stop", function (item) {
  let ids = "";
  $(".uk-sortable tr").each(function () {
    id = $(this).data("id");
if (ids == "") {
  ids = id;
} else {
  ids = ids + ", " + id;
}
   // console.log(ids);
 });
 // console.log($(this).data('id'));
 $.ajax({
url: "/admin/cost/list-update/",
type: "GET",
dataType: "json",
data: {
  ids: "" + ids,
},
timeout: 10000,
 })
.done(function (result) {
  UIkit.notification(`?????????????????`, "success");
  //location.reload(true);
})
.fail(function (XMLHttpRequest, textStatus, errorThrown) {
  console.log(textStatus);
  console.log(errorThrown);
 });
});

PHP Snippet 2:

public function listUpdate()
{

    // ----------------------------------------
    // ????
    // ----------------------------------------
    $now = Chronos::now();
    try {
        // ----------------------------------------
        // ?????
        // ----------------------------------------
        $this->loadModel('Specs');

        if ($this->request->is('ajax')) {
            // -------------------------------------------
            // ????????????/ Get request params
            // -------------------------------------------
            $ids = $this->request->getQuery('ids');
            // -------------------------------------------
            // seperate ids/???ID
            // -------------------------------------------
            $arr = explode(',', $ids);

            for ($i = 1; $i <= count($arr); $i ++) {
                $spec = $this->Specs->find();//get the specs
                $connection = ConnectionManager::get('default');
                $connection->begin();
                //select the spec
                $spec->where([
                    'Specs.spec_id' => $arr[$i - 1],
                ]);
                //update sort column
                $sp = array(
                    'sort' => $i
                );
                
                //change query to entitiy
                $data = $spec->first();
                //update entity info
                $data['updated_at'] = $now;
                $data['updated_by'] = $this->loginUserInfo['admin_id'];
                
                $this->Specs->patchEntity($data, $sp);
                $this->Specs->saveOrFail($data);
                $connection->commit();
            }
        }
        $status = true;
        $response = $this->response;
        $response = $response->withType('application/json');
        $response = $response->withStringBody(json_encode(compact('status')));

        return $response;
    } catch (Exception $e) {
        // ??????????????
        $connection->rollback();

        throw $e;
    }
}