php - 在 laravel 5 中处理复杂的查询
问题描述
我有复杂查询的简单任务,完成了 50%,其余部分需要帮助。
逻辑
- 我有登陆页面,我选择类别,然后在该类别下选择规格,与这两个过滤器相关的产品将显示在登陆页面中。
this is done
- 当我选择类别而不选择任何规格时,我还希望有登录页面,它会显示与该类别相关的所有产品,无论它们有什么规格。
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:我知道我这里有两个主要问题
- 我的 if 语句不正确
- 我的 else 部分需要修复(但在修复 if() 之前我无法看到 else 部分的结果)
任何想法?
解决方案
解决了
我将我的 if 部分更改为下面的代码,现在它运行良好
$spac = DB::table('landing_specifications')->where('landing_id', $landing->id)->first();
if($spac){
// rest of it...
希望能帮助到你。
推荐阅读
- excel - 如何使用 OFFSET() 函数返回不同选项卡中的行?
- java - 无法执行目标 org.sonarsource.scanner.maven 对于工件 {null:null:null:jar}:groupId 不能为空
- powershell - 为什么论证没有生效?
- python - 使用 fit_generator() 在数据生成器中应用 model.predict() 时出现问题
- python - 列表理解中的两个值
- c# - 具有默认值的枚举的 C# Swagger 生成
- css - 在媒体查询中设置 CSS 变量可靠吗?
- python - 如何获取用户角色
- angular - 为什么我必须单击两次才能执行我的功能?
- python-3.x - 不使用任何软件包的 2d 绘图仪