Php 创建一个查询,该查询将检查数量是否在数量范围内,并使用laravel中的jquery从产品id输出一定的基数

Php 创建一个查询,该查询将检查数量是否在数量范围内,并使用laravel中的jquery从产品id输出一定的基数,php,jquery,laravel,Php,Jquery,Laravel,我正在使用销售发票应用程序,它有一个自动完成jquery脚本 它自动加载放置在隐藏字段中的产品id。这是我的自动完成脚本 //autocomplete script $(document).on('focus','.autocomplete_txt',function(){ type = $(this).data('type'); if(type =='product_code' )autoType='product_code'; if(type =='product_name

我正在使用销售发票应用程序,它有一个自动完成jquery脚本

它自动加载放置在隐藏字段中的产品id。这是我的自动完成脚本

//autocomplete script
$(document).on('focus','.autocomplete_txt',function(){
  type = $(this).data('type');

  if(type =='product_code' )autoType='product_code'; 
  if(type =='product_name' )autoType='name'; 
  if(type =='product_price' )autoType='price'; 
  if(type =='product_cost' )autoType='cost'; 
  if(type =='quantity' )autoType='quantity'; 
  if(type =='product_id' )autoType='id'; 

   $(this).autocomplete({
       minLength: 0,
       source: function( request, response ) {
            $.ajax({
                url: "{{ route('searchaSaleItems') }}",
                dataType: "json",
                data: {
                    term : request.term,
                    type : type,
                },

                success: function(data) {
                  if(!data.length){
                    var notFound = [
                      {
                      label: 'No matches found', 
                      value: response.term
                      }
                    ];
                      response(notFound);
                  } else {
                    var array = $.map(data, function (item) {
                      return {
                          label: item[autoType],
                          value: item[autoType],
                          data : item
                      }
                    });
                    response(array)
                  }
                }
            });
       },
        select: function( event, ui ) {
          var data = ui.item.data; 
          var arr = []; 

          id_arr = $(this).attr('id');
          id = id_arr.split("_");
          elementId = id[id.length-1];

          $('.product_code').each(function() {
            arr.push($(this).val());
          });

          // added logic to check if there are duplicates in the array we just populated with product codes, checked against the passed in product code 
          if(arr.includes(data.product_code)) {

            $('#add').prop('disabled', true);
            $('#submit').prop('disabled', true);
            $('#row'+rowCount+'').addClass('danger');
            // $('#duplicate_entry_'+elementId).text('Duplicate entry. Replace product code to continue. ');
            alert('Duplicate entry. Replace product code to continue. ');
          } else {
            $('#add').prop('disabled', false);
            $('#submit').prop('disabled', false);
            $('#row'+rowCount+'').removeClass('danger');

            $('#product_code_'+elementId).val(data.product_code).prop('readonly', true);
            $('#product_name_'+elementId).val(data.name).prop('readonly', true);
            $('#product_cost_'+elementId).val(data.cost);
            $('#product_price_'+elementId).val(data.price).prop('min', data.price);
            $('#product_id_'+elementId).val(data.id);
            $('#quantity_'+elementId).prop('max', data.quantity);
            $('#quantity_warning_'+elementId).text('You have '+data.quantity+' in your stocks');
            $('#price_minimum_'+elementId).text('The minimum price is '+data.price);
          }
        }
   });
});
这是我的控制器的查询

public function salesResponse(Request $request){
    $query = $request->get('term','');
    $wh2Summaries=Warehouse2StockSummaries::with('product');

    if($request->type == 'product_code'){
        $wh2Summaries->whereHas('product', function ($q) use ($query) {
            $q->where('product_code', 'LIKE', '%' . $query . '%');
        }); 
    }

    $wh2Summaries=$wh2Summaries->get();        
    $data=array();
    foreach ($wh2Summaries as $wh2Summary) {
        $data[]=array(
            'product_code'=>$wh2Summary->product->product_code,
            'name'=>$wh2Summary->product->name,
            'price'=>$wh2Summary->product->selling_price,
            'cost'=>$wh2Summary->product->price,
            'quantity'=>$wh2Summary->qty_in-$wh2Summary->qty_out,
            'id'=>$wh2Summary->product->id
        );
    }

    if(count($data))
        return $data;
    else
        return [
            'product_code'=>''
        ];    
}
整个过程一直在进行,直到我的老板想添加另一个功能,他称之为“数量范围”,在某个范围内有自己的价格,该价格应动态显示在价格字段中,因此假设1-10台电脑的价格为100美元,11-20台电脑的价格为200美元,依此类推。。。因此,我创建了另一个表,我称之为“价格范围”,它为特定产品提供了多个数量范围

我在产品和价格范围之间建立了一种关系

产品型号

class Products extends Model
{
    // use SoftDeletes;

    protected $fillable = [
        'product_code',
        'name',
        'categories_id',
        'wh1_limit_warning',
        'wh2_limit_warning',
        'price',
        'selling_price',
        'user_id'
    ];

    // protected $dates = ['deleted_at'];

    public function priceRanges()
    {
        return $this->hasMany('App\Priceranges', 'product_id', 'id');
    }
}
class Priceranges extends Model
{
    protected $table = 'priceranges';
    protected $fillable = [
        'product_id',
        'qty_from',
        'qty_to',
        'amount',
    ];

    public function products()
    {
        return $this->belongsTo('App\Products', 'id', 'product_id');
    }    
}
价格范围型号

class Products extends Model
{
    // use SoftDeletes;

    protected $fillable = [
        'product_code',
        'name',
        'categories_id',
        'wh1_limit_warning',
        'wh2_limit_warning',
        'price',
        'selling_price',
        'user_id'
    ];

    // protected $dates = ['deleted_at'];

    public function priceRanges()
    {
        return $this->hasMany('App\Priceranges', 'product_id', 'id');
    }
}
class Priceranges extends Model
{
    protected $table = 'priceranges';
    protected $fillable = [
        'product_id',
        'qty_from',
        'qty_to',
        'amount',
    ];

    public function products()
    {
        return $this->belongsTo('App\Products', 'id', 'product_id');
    }    
}
从那以后,我不知道下一步该怎么办:(

我想要达到的条件是,一旦用户输入数量,检查隐藏字段中的产品id(由autocomplete提供) 在priceranges表中可用,如果可用,请检查数量属于哪个范围,然后输出金额


请您帮助我使用jQuery完成这项工作好吗?我对jQuery了解不多。提前感谢您!

我认为您应该在模型中修改的第一件事是产品表中的价格,您应该删除它。这样,所有产品价格都将放在一个位置:Priceranges表。因此,您可以设置default“qty\u from”到0,“qty\u to”到“nullable()”。如果“qty\u to”为空,则表示价格在“qty\u from”和无穷大之间为“X”

改变了,我们转到控制器

public function salesResponse(Request $request){
    $query = $request->get('term','');
    $wh2Summaries=Warehouse2StockSummaries::with('product');

    if($request->type == 'product_code'){
        $wh2Summaries->whereHas('product', function ($q) use ($query) {
            $q->where('product_code', 'LIKE', '%' . $query . '%');
        }); 
    }

    $wh2Summaries=$wh2Summaries->get();        
    $data=array();
    foreach ($wh2Summaries as $wh2Summary) {

        $qty = $wh2Summary->qty_out;

        $price = $wh2Summary->product->priceRanges()
                 ->where('qty_from', '<=', $qty)
                 ->where(function ($q) use($qty){
                     $q->where('qty_to', '>=', $qty)->orWhere('qty_to', null);
                  })->first();
        //in this way, you need every product has their priceRange
        if(isset($price->id)){
            $price = $price->amount; // the price in range chosen 
        }else{ //get the price from original table, if you does not has removed that
            $price = $wh2Summary->product->selling_price;
        }

        $data[]=array(
            'product_code'=>$wh2Summary->product->product_code,
            'name'=>$wh2Summary->product->name,
            'price'=> $price,
            'cost'=>$wh2Summary->product->price,
            'quantity'=>$wh2Summary->qty_in-$wh2Summary->qty_out,
            'id'=>$wh2Summary->product->id
        );
    }

    if(count($data))
        return $data;
    else
        return [
            'product_code'=>''
        ];    
}

公共功能salesResponse(请求$Request){
$query=$request->get('term','');
$wh2Summaries=Warehouse2StockSummaries::with('product');
如果($request->type=='product\u code'){
$wh2Summaries->whereHas('product',function($q)use($query){
$q->where('product_code','LIKE','%.$query'%');
}); 
}
$wh2Summaries=$wh2Summaries->get();
$data=array();
foreach($WH2汇总为$WH2汇总){
$qty=$WH2SUMARY->qty\U out;
$price=$wh2Summary->product->priceRanges()
->其中('qty\U from','=',$qty)->或其中('qty\U to',null);
})->第一个();
//这样,你需要每种产品都有其价格范围
如果(设置($price->id)){
$price=$price->amount;//所选范围内的价格
}否则{//从原始表中获取价格,如果您没有删除该表
$price=$wh2Summary->product->售价;
}
$data[]=数组(
“产品代码”=>$WH2摘要->产品->产品代码,
'name'=>$wh2Summary->product->name,
“价格”=>美元价格,
“成本”=>$WH2汇总->产品->价格,
“数量”=>$WH2汇总->数量输入-$WH2汇总->数量输出,
'id'=>$wh2Summary->product->id
);
}
如果(计数($数据))
返回$data;
其他的
返回[
“产品代码”=>“
];    
}
这样,您只需要更改控制器,而不需要更改JQuery


希望这对你有帮助

我会在我的
产品
模型中添加一个函数,给定一个数字,该函数将返回正确的价格

公共函数getCorrectPrice($number){
$pricelanges=$this->pricelanges;
foreach($priceRanges作为$range){
如果($number>=$range->qty\u from&$number<$range->qty\u to){
返回$range->amount;
}
}
return$this->price;//如果没有有效范围,则返回默认的产品价格
}
现在修改ajax调用以包括用户插入的数量:

数据:{
期限:request.term,
类型:类型,
数量:数量,//从用户处获取数量
},
在控制器中:

  $quantity = $request->get('quantity');
  $price = $wh2Summary->product->getCorrectPrice($quantity);
注意:为了获得更好的性能,我建议您在产品中加入以下价格范围:

$wh2Summaries=Warehouse2StockSummaries::with('product.priceRanges');

尝试以下产品::where('id',13)->priceRanges()->where('qty_from','=',20)->get();首先,你的
产品()
价格范围中的关系不应该是
$this->belongsTo
而不是
有很多
?Hi@carlosafon这样的关系可以与hasMany@Lito即使有效也不意味着它是正确的,这是巧合编程你是对的@CarlosAfonso应该是$this->belongsTo。我更新了我的问题谢谢@HerickC。有没有一种方法可以在不更改产品表的情况下解决问题?我发布的代码有一个验证,如果产品没有
价格范围
,这将从原始表中获得
$wh2Summary->product->selling_price
。更改产品表,将是最佳做法,这样,产品价格将始终在
价格范围内
。Hi@HerickC当我添加==>$qty=$request->input('quantity')时,搜索查询不起作用$price=$wh2Summary->product->priceRanges()->where('qty_from','>=',$qty)->where(函数($q)使用($qty){$q->where('qty_to','Thank@gbalduzzi!我现在就试试,我会让你知道结果的。请注意,我认为你希望你的字段
price
有这种行为。如果你想在产品字段
selling_price
中有这种行为,只需更改
getCorrectPrice
函数中的最后一个返回语句当我在数据{}中添加“数量:数量”时,或者当我添加$quantity=$request->get('quantity');$price=$wh2Summary->product->getCorrectPrice($quantity');在我的控制器中,您需要从用户处获取数量并将其放入变量c中