首页 > 解决方案 > 在 laravel 5 中处理复杂的查询

问题描述

我有复杂查询的简单任务,完成了 50%,其余部分需要帮助。

逻辑

  1. 我有登陆页面,我选择类别,然后在该类别下选择规格,与这两个过滤器相关的产品将显示在登陆页面中。this is done
  2. 当我选择类别而不选择任何规格时,我还希望有登录页面,它会显示与该类别相关的所有产品,无论它们有什么规格。need help for this

代码

这是我的控制器i commented each part for better understanding

public function landings($slug){
    $landing = Landing::where('slug', $slug)->Status('Active')->firstOrFail(); //find landing page

    //getting landing pages category id (in case one landing page have several category involved)
    $cat = DB::table('landing_categories')->where('landing_id', $landing->id)->get();
    foreach ($cat as $key) {
      $id[] = $key->category_id;
    }

    // i just add this to filter landing without specifications for if statement below **not sure about this yet**)
    $spac = DB::table('landing_specifications')->where('landing_id', $landing->id)->get();

    // this is where things happen (first $prod is responsible for landing with specifications and working fine, **else part** need fix to show landings without specifications.
    if($spac != null){
      //old
      $prod = DB::table('landing_specifications')->where('landing_id', $landing->id)
      ->join('product_subspecification', function ($keys) {
          $keys->on('product_subspecification.subspecification_id', '=', 'landing_specifications.subspecification_id');
      })
      ->join('products', 'products.id', '=', 'product_subspecification.product_id')
      ->whereIn('products.category_id', $id)
      ->groupby('products.id')
      ->paginate(12);
    }else{
      //new
      $prod = DB::table('landing_categories')->where('landing_id', $landing->id)
      ->join('products', 'products.category_id', '=', 'landing_categories.category_id')
      ->whereIn('products.category_id', $id)
      ->groupby('products.id')
      ->paginate(12);
    }


    return view('front.landing', compact('landing', 'prod'));
  }

希望我在上面代码中的评论对您避免误解有用。

PS:我知道我这里有两个主要问题

  1. 我的 if 语句不正确
  2. 我的 else 部分需要修复(但在修复 if() 之前我无法看到 else 部分的结果)

任何想法?

标签: phplaravel

解决方案


解决了

我将我的 if 部分更改为下面的代码,现在它运行良好

$spac = DB::table('landing_specifications')->where('landing_id', $landing->id)->first();

if($spac){
// rest of it...

希望能帮助到你。


推荐阅读