【问题标题】:Getting ajax based data in laravel在 laravel 中获取基于 ajax 的数据
【发布时间】:2018-07-16 05:21:23
【问题描述】:

我尝试做一个查找器(一种高级搜索),我走了一半,我遇到了我的搜索查询的第三部分的问题。

逻辑

  1. 选择类别
  2. 选择子类别
  3. 在子类别中选择产品规格
  4. 在子类别中选择品牌

基本上用户会选择类别,然后选择该类别的子类别till here I've done,然后该子类别产品的所有规格和品牌将被呈现给选择。

问题

我的问题是从选择中获取规格和品牌 子类别。

我想根据所选子类别获取这些信息的原因是因为每个子类别产品都有不同的品牌和规格,例如我不想在用户选择 mouse 子类别时显示 cpu 规格!任何类型的鼠标都没有 cpu,这就是全部原因。

代码

blade

<form action="" class="mt-20">
                <div class="col-md-3">
                    <label for="category_id">category</label>
                    <select name="category_id" class="form-control">
                        <option value="">Select Category</option>
                        @foreach($findercategories as $category)
                            <option value="{{$category->id}}">{{$category->title}}</option>
                        @endforeach
                    </select>
                </div><!-- end col-md-3 -->
                <div class="col-md-3">
                    <label for="subcategory_id">subcategory</label>
                    <select name="subcategory_id" class="form-control">
                        <option value="">Select Subcategory</option>
                    </select>
                </div><!-- end col-md-3 -->
                <div class="col-md-3">
                    <label for="specification_id">specifications</label>
                    <select name="specification_id" class="form-control">
                        <option value="">Select Specification</option>
                    </select>
                </div><!-- end col-md-3 -->
                <div class="col-md-3">
                    <label for="brand_id">brands</label>
                    <select name="brand_id" class="form-control">
                        <option value="">Select Brand</option>
                    </select>
                </div><!-- end col-md-3 -->
                <div class="row">
                    <div class="col-md-3 col-md-offset-9">
                        <button style="margin: 20px;" class="pull-right btn btn-info" type="submit">Find</button>
                    </div>
                </div>
              </form>

Javascript

<script type="text/javascript">
  $(document).ready(function() {
    $('select[name="category_id"]').on('change', function() {
      var categoryID = $(this).val();
      if(categoryID) {
      $.ajax({
        url: '{{ url('getSubCategories') }}/'+encodeURI(categoryID),
        type: "GET",
        dataType: "json",
        success:function(data) {
        $('select[name="subcategory_id"]').empty();
        $.each(data, function(key, value) {
            $('select[name="subcategory_id"]').append('<option class="form-control" value="'+ value['id'] +'">'+ value['title'] +'</option>');
            });
        }
      });
      }else{
        $('select[name="subcategory_id"]').empty();
      }
    });
  });
</script>

<script type="text/javascript">
  $(document).ready(function() {
    $('select[name="subcategory_id"]').on('change', function() {
      var subcategoryID = $(this).val();
      if(subcategoryID) {
      $.ajax({
        url: '{{ url('getspecifications') }}/'+encodeURI(subcategoryID),
        type: "GET",
        dataType: "json",
        success:function(data) {
        $('select[name="specification_id"]').empty();
        $.each(data, function(key, value) {
            $('select[name="specification_id"]').append('<option class="form-control" value="'+ value['id'] +'">'+ value['title'] +'</option>');
            });
        }
      });
      }else{
        $('select[name="specification_id"]').empty();
      }
    });
  });
</script>

controller

//get categories list
$findercategories = Category::ofStatus('Active')->get();

//finder (subcategories)
    public function getSubCategories($id){
        $subcategory = Subcategory::where('category_id', $id)->get();
        return response()->json($subcategory);
    }

//finder (specifications + brands)
    public function getspecifications($id){
        $product = Product::where('subcategory_id', $id)->get();
        $productsubsp = DB::table('product_subspecification')->where('product_id', $product)->get();
        $specifications = $productsubsp;
        return response()->json($specifications);
    }

routes

Route::get('/getSubCategories/{id}', 'frontend\SearchController@getSubCategories');
Route::get('/getspecifications/{id}', 'frontend\SearchController@getspecifications');

额外(只是为了清楚我试图获取的数据)

  1. 我的产品品牌保存在products 列中的表中 命名为brand_id
  2. 我的产品规格保存在名为的第三个表中 product_subspecification 将得到 id product_idsubspecification_id

这就是我在前端获取这些信息的方式:

品牌

{{$product->brand->title}}

和规范

在控制器中

$specifications = $product->subspecifications->mapToGroups(function ($item, $key) {
        return [$item->specification->title => $item];
    });

在刀片中

@foreach($specifications as $specificationtitle => $specificationcollection)
<tr>
<th style="width:150px;">{{ $specificationtitle }}</th>
<td class="text-left">
@foreach($specificationcollection as $subspecification)
{{$subspecification->title}}
@endforeach
</td>
</tr>
@endforeach

返回如下:

CPU 核心 I5 核心 I3 核心 I7

RAM 2 GIG 4 GIG

更新

我设法在规格下拉列表中获得了结果,但是我无法将我的所有产品都归入所选子类别 I only can get last product 而不是全部。

代码

这是我目前获得结果的方式

public function getspecifications($id){
            //find products under subcategory
             $product = DB::table('products')
                            ->where('subcategory_id', $id)
                            ->get();
                            foreach($product as $pp) {
                            }
            $specificationsw = $pp->id; //get products id (currently has issue, only gets 1)

            // find products specification with same product id
            $specificationss = DB::table('product_subspecification')
                            ->where('product_id', $specificationsw)->get();
                            foreach($specificationss as $dd) {
                            }
            $specificationsss = $dd->subspecification_id; //get specifications id from product_subspecification table


            // get specifications title base on table above
           $specifications = DB::table('subspecifications')
                            ->where('id', $specificationsss)->get();
        return response()->json($specifications);
    }

知道如何获得我所有的产品id 而不是只有最后一个which i'm getting currently

更新2

我将控制器更改为以下代码,现在我可以从子类别中获取我的所有产品:

public function getspecifications($id){
            //find products under subcategory
            $product = DB::table('products')
                            ->where('subcategory_id', $id)
                            ->get();
            $date = array();
            foreach ($product as $stan) {
                $date[] = $stan->id;
            }
            $specificationsw = $date; //get products id (currently has issue, only gets 1)

            // find products specification with same product id
            $specificationss = DB::table('product_subspecification')
                            ->where('product_id', $specificationsw)->get();
            $date2 = array();
            foreach ($specificationss as $stan2) {
                $date2[] = $stan2->subspecification_id;
            }
            $specificationsss = $date2; //get specifications id from product_subspecification table

            // get specifications title base on table above
            $specifications = DB::table('subspecifications')
                            ->where('id', $specificationsss)->get();
            $date3 = array();
            foreach ($specifications as $stan3) {
                $date3[] = $stan3;
            }           
            $specifications = $date3;
        return response()->json($specifications);
    }

现在这是我的dd 结果:

dd($specificationsw); products dd 是产品的 id 2 products

array:2 [▼
  0 => 27
  1 => 38
]

dd($specificationsss);product_subspecification 表结果only return values of product id 27. nothing for product id 38!

array:2 [▼
  0 => 5
  1 => 8
]

dd($specifications); 我函数 i get this title in my ajax code in front-end 的最后一部分的结果,但正如您看到的有关 subspesification id 8product id 38 的信息丢失了。

array:1 [▼
  0 => {#722 ▼
    +"id": 5
    +"title": "4 GIG"
    +"specification_id": 2
    +"created_at": "2017-12-04 00:00:00"
    +"updated_at": "2017-12-04 00:00:00"
  }
]

【问题讨论】:

  • 突然,在问题的最后,我们学到了一些涉及&lt;th&gt;&lt;\th&gt;&lt;td&gt;&lt;\td&gt; 的东西。为什么?
  • 从我的产品视图来看,这只是为了展示我如何返回规格。不包括我的问题。正如我所说的额外(只是为了清楚我试图获取的数据)
  • 如果它与问题无关,我建议将其省略,否则像我这样的人会感到困惑。
  • 我认为它是相关的,因为我尝试在我的查找器中获取完全相同的数据,所以人们知道我想要实现什么,但如果我以后看到它会导致问题,我可能会采取你的建议并将其删除。无论如何,您知道如何解决我的问题吗?
  • 好的,祝你好运。

标签: javascript php ajax laravel search


【解决方案1】:

已解决

我在这里为有需要的人解决了我的问题:

说明:

  1. 控制器的第一种方法将根据所选的子类别 类别 ID。
  2. 第二种方法将根据选定的子类别显示specifications,在我的情况下,note 的规格存储在他们的表中,并且与我的产品相关,sync method 在第三个表中。 (将仅显示该子类别下的产品中使用的规格)
  3. 第三种方法将根据选定的子类别显示brands(仅显示在该子类别下的产品中使用的品牌)

Controller 方法

//finder (find subcategories base on selected category)
    public function getSubCategories($id){
        $subcategory = Subcategory::where('category_id', $id)->get();
        return response()->json($subcategory);
    }

    //finder (show specifications base on selected subcategory)
    public function getspecifications($id){
            $specifications = DB::table('products')
                        ->where('subcategory_id', $id)
                        ->join('product_subspecification', 'product_subspecification.product_id', '=', 'products.id')
                        ->join('subspecifications', 'subspecifications.id', '=', 'product_subspecification.subspecification_id')
                        ->groupBy('subspecifications.id')
                        ->get();
            return response()->json($specifications);
    }

    //finder (show brands base on selected subcategory)
    public function getbrands($id){
        $specifications = DB::table('products')
                    ->where('subcategory_id', $id)
                    ->join('brands', 'brands.id', '=', 'products.brand_id')
                    ->groupBy('brand_id')
                    ->get();
                    return response()->json($specifications);
    }

重要提示:为了避免specificationsbrands 出现重复的结果,我使用了groupBy

Routes

Route::get('/getSubCategories/{id}', 'frontend\SearchController@getSubCategories');
Route::get('/getspecifications/{id}', 'frontend\SearchController@getspecifications');
Route::get('/getbrands/{id}', 'frontend\SearchController@getbrands');

Scripts

<script type="text/javascript">
  $(document).ready(function() {
    $('select[name="category_id"]').on('change', function() {
      var categoryID = $(this).val();
      if(categoryID) {
      $.ajax({
        url: '{{ url('getSubCategories') }}/'+encodeURI(categoryID),
        type: "GET",
        dataType: "json",
        success:function(data) {
        $('select[name="subcategory_id"]').empty();
        $.each(data, function(key, value) {
            $('select[name="subcategory_id"]').append('<option class="form-control" value="'+ value['id'] +'">'+ value['title'] +'</option>');
            });
        }
      });
      }else{
        $('select[name="subcategory_id"]').empty();
      }
    });
  });
</script>

<script type="text/javascript">
  $(document).ready(function() {
    $('select[name="subcategory_id"]').on('change', function() {
      var subcategoryID = $(this).val();
      if(subcategoryID) {
      $.ajax({
        url: '{{ url('getspecifications') }}/'+encodeURI(subcategoryID),
        type: "GET",
        dataType: "json",
        success:function(data) {
        $('select[name="specification_id"]').empty();
        $.each(data, function(key, value) {
            $('select[name="specification_id"]').append(
                  "<option class='form-control' value='"+ value['id'] +"'>"+ value['title'] +"</option>"
                  );
            });
        }
      });
      }else{
        $('select[name="specification_id"]').empty();
      }
    });
  });
</script>

<script type="text/javascript">
  $(document).ready(function() {
    $('select[name="subcategory_id"]').on('change', function() {
      var subcategoryID = $(this).val();
      if(subcategoryID) {
      $.ajax({
        url: '{{ url('getbrands') }}/'+encodeURI(subcategoryID),
        type: "GET",
        dataType: "json",
        success:function(data) {
        $('select[name="brand_id"]').empty();
        $.each(data, function(key, value) {
            $('select[name="brand_id"]').append('<option class="form-control" value="'+ value['id'] +'">'+ value['title'] +'</option>');
            });
        }
      });
      }else{
        $('select[name="brand_id"]').empty();
      }
    });
  });
</script>

【讨论】:

    猜你喜欢
    • 2016-12-12
    • 2015-03-29
    • 2019-01-14
    • 1970-01-01
    • 2020-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多