I am preparing an e-commerce site. I have two tables linked by Releationship. The first table is Products and the second is ProductAttributes. It is linked by product_id in two tables. When I query my Products table, in my Product model file
public function attributes()
{
return $this->hasMany(ProductAttribute::class, 'product_id');
}
I want to extract only eligible products using relation. The query is like this:
$products = Product::select('id', 'slug', 'p_image', 'name', 'active', 'low_sell_price', 'combine_name')
->where('active', 'a')
->whereHas('categories', function ($query) {
$query->where('slug->tr', $this->slug);
})
->whereHas('attributes' , function ($attrquery) {
$attrquery->whereIn('value', $this->select_filter_attr);
})
->paginate(100);
But the problem is, when I do whereIn('value', ['2021','LOW'])
using the value field in the ProductAttributes
table, it pulls all the products with both 2021 and LOW values, while I want it to pull the products with both 2021 and LOW fields at the same time. How do I do this, thanks in advance.
You can achieve this like this:
$products = Product::select('id', 'slug', 'p_image', 'name', 'active', 'low_sell_price', 'combine_name')
->where('active', 'a')
->whereHas('categories', function ($query) {
$query->where('slug->tr', $this->slug);
})
->whereHas('attributes' , function ($attrquery) {
foreach($this->select_filter_attr as $attr) {
$attrquery->where('value', $attr);
}
})
->paginate(100);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.