我尝试在您打折产品的品牌中进行搜索。
折扣表会保存product_id
,产品会保存brand_id
以下是我如何获得折扣产品:
$promotions = Discount::with('products')->Valid()->orderby('id', 'desc')->paginate(12);
这是我的品牌:
$brandspromotion = Brand::OfStatus('Active')->get();
这是我的完整代码:
// Index `Promotion` page (where all results are mixed from all brands etc.)
public function promotions() {
$promotions = Discount::with('products')->Valid()->orderby('id', 'desc')->paginate(12); // get all discounted products
$options = Option::all(); // for my sidebar only
$brands = Brand::OfStatus('Active')->get(); // for my sidebar only
$brandspromotion = Brand::OfStatus('Active')->get();
//this has to be change to some query in order to only get brands of discounted products
//result of this i will use in drop-down select box.
return view('front.promotions', compact('promotions', 'options', 'brandspromotion', 'brands'));
}
// this function will take care of chosen brand result
public function brandspromotions($slug) {
//
}
任何想法?
我将查询更改为以下代码:
$promotions2 = Discount::with('products')->Valid()->orderby('id', 'desc')->get();
foreach($promotions2 as $brandpro){
$brand_id = $brandpro->products->brand_id;
}
$brandspromotion = Brand::OfStatus('Active')
->where('id', '=', $brand_id)->get();
它正在运作但只获得1
品牌,我的循环必须出错!
我尝试使用map
这是我的代码:
$promotions2 = Discount::with('products')->Valid()->get();
$grouped = $promotions2->map(function ($item, $key) {
return $item->products->brand_id;
});
$grouped->all();
// dd($grouped);
$brandspromotion = Brand::OfStatus('Active')
->where('id', '=', $grouped)->get();
结果就像:
Collection {#713 ▼
#items: array:4 [▼
0 => 2
1 => 1
2 => 2
3 => 1
]
}
我想要lenovo
(身份证明:1)和lg
(身份证明2),但我只能获得lg
。
$promotions2 = Discount::with('products')->Valid()->get();
$grouped = $promotions2->mapToGroups(function ($item, $key) {
return [$item->products->brand_id => $item->products->brand_id];
});
dd($grouped);
$brandspromotion = Brand::OfStatus('Active')
->where('id', '=', $grouped->all())->get();
结果:
Collection {#704 ▼
#items: array:2 [▼
2 => Collection {#710 ▼
#items: array:2 [▼
0 => 2
1 => 2
]
}
1 => Collection {#703 ▼
#items: array:2 [▼
0 => 1
1 => 1
]
}
]
}
问题:
我想要
lenovo
(身份证明:1)和lg
(身份证明2),但我只能获得lg
。
答案 0 :(得分:0)
您可以使用whereIn
来传递值数组:
$brandspromotion = Brand::OfStatus('Active')->whereIn('id', $grouped)->get();