大家好,我正在开发一个列出和过滤产品的网站。
我的问题是产品表有 40000 行,product_details 有 210 万行。
我想用product_details表过滤产品表
我的代码是
$sliced = array_values(array_slice($req_val, 3));
$products = Products::where('status', 1)
->where('s_part', $req_val[0])
->where('main_category', $req_val[1])
->where('sub_category', $req_val[2])
->join('product_details', 'products.sapcode', '=', 'product_details.sapcode')
->where(function ($query) use ($sliced, $keys) {
foreach ($sliced as $index => $value) {
$key = $keys[$index];
$query->orWhere(function ($query) use ($value, $key) {
$query->where('product_details.value', $value)
->where('product_details.name', $key);
});
}
})
->get('products.sapcode');
$products = $products->map(function($item){
return $item->sapcode;
});
$counts = array_count_values($products->toArray());
$threshold = count($sliced);
$filtered = array_filter($counts, function($count) use ($threshold) {
return $count >= $threshold;
});
$result = array_keys($filtered);
$products = Products::whereIn('products.sapcode', $result)->get();
return response()->json($products);
产品型号连接到产品表 产品详细信息已连接到产品详细信息
如何连接和过滤这两个表。最好的方法是什么。
一种方法是你知道如何做:一个带有连接的雄辩构建器。 我认为更容易阅读的解决方案是定义模型中的关系。我猜你这里有1:M或N:M关系,所以使用hasMany,belongsToMany/belongstoOne,然后你可以像这样使用whereHas:
->wehereHas('productDetails', function(Builder $query) {
// here you filter by product details
$query->where('column', $value);
}