Laravel 使用 id 数组获取价格列的总数

我有 jquery 将 id 数组发送到控制器,每个 id 在数据库中都有价格,我想得到 ajax 发送的那些 id 的总价格,正如你在下面看到的 id 数组,我不知道是什么在控制器中写入以获取这些 id 的总价格


array:3 [▼

 0 => "36"

  1 => "274"

   2 => "38"

 ]



 $('.option__choices input').on('change', function() { 

   var checkid = [];


        $.each($("input[name='customizecheck']:checked"), function(){            

            checkid.push($(this).val());

        });

        $.ajax({

            url:'/writer/getcustPrice',

            type: 'get',

              data: {

                    '_token': $('input[name=_token]').val(),

                    'checkid': checkid

                },


       success: function(data){

            },


            error:function(data){

            }


      });  });

控制器


 public function getcustPrice(Request $request)

   {


 if($request->ajax())

{


 foreach($request->input('checkid') as $key => $value) {


  $allids = CustomizeProduct::findOrFail($request->input('checkid'));        


  $price=$allids->customize_price;


    }

}


郎朗坤
浏览 229回答 2
2回答

汪汪一只猫

您需要创建一个总变量,并需要为每个通过的 checkId 添加价格,如下所示:public function getcustPrice(Request $request){   if($request->ajax()){        $totalPrice = 0;        foreach($request->input('checkid') as $key => $value) {            $allids = CustomizeProduct::findOrFail($value);            $price = $allids->customize_price;            $totalPrice += $price;        }        return Response::json( $totalPrice );    }}希望对你有帮助!!

aluckdog

你有没有这样检查,$price = 0;foreach($request->input('checkid') as $key => $value) {  $allids = CustomizeProduct::findOrFail($request->input('checkid'));          $price += $allids->customize_price;}return $price;
打开App,查看更多内容
随时随地看视频慕课网APP