如何改善Laravel查询

时间:2019-06-19 14:58:16

标签: php laravel laravel-5 eloquent

$pfilters = ProductFilters
        ::whereIn('Tb_Product_filters.filter_value', $values)
        ->groupBy('Tb_Product_filters.product_id')
        ->join("Tb_Products","Tb_Products.id","Tb_Product_filters.product_id")
        ->join('Tb_Identities', 'Tb_Identities.id', '=', 'Tb_Products.employee_id')
        ->select(
            "Tb_Products.*",
            "Tb_Identities.first_name as fname",
            "Tb_Identities.last_name as lname"
        )
        ->get()
        ->toArray();

此查询为我提供了values数组中的所有产品,我只希望product中包含所有表示例如

的值

如果我的值= [1,2,3]

以上陈述使我知道任何具有value_id = 123

的产品

我只希望产品收集3个属性,这意味着只有产品具有value_id = 123的产品应该在许多行中进行搜索。

我有4张桌子 产品展示 过滤器 filter_value products_filters

首先,我们从过滤器开始

任何过滤器具有一个或多个filter_values 示例:filter = color,filters_value = [red,blue,green],您现在它们之间的关系取决于filter_id作为forgen键

产品表:创建产品时,我将选择产品过滤条件和值 例如:iphone = [color:glod,rom:128GB] 所以我会将它们存储在products_filters

products_filter表将包含; product_id,filter_id,filter_value

所以可以说我想要带有color:red和rom 64GB的产品吗?

2 个答案:

答案 0 :(得分:0)

尝试一下

$pfilters = ProductFilters::select("
SELECT 
TB_PRODUCTS.*,
Tb_Identities.first_name as fname,
Tb_Identities.last_name as lname 
FROM Tb_Product_filters 
JOIN Tb_Products ON TB_Products.id=Tb_Product_filters.product_id 
JOIN Tb_Identities ON Tb_Identities.id=TB_Products.employee_id")
WHERE (Tb_Product_filters.filter_value = '$values[0]' OR Tb_Product_filters.filter_value = '$values[1]' OR Tb_Product_filters.filter_value = '$values[2]')

根据您的数组中有多少个值,添加“或Tb_Product_filters.filter_value = $ values [X]”

答案 1 :(得分:0)

i已修复 这就是答案

$values = explode(",", $request->input('values'));
        $organization_id = $request->input('organization_id');
        $prodicts_filters_ids = ProductFilters::whereIn('filter_value', $values)->groupBy("product_id")->select("product_id")->get()->toArray();
        $products_have_values = [];
        foreach ($prodicts_filters_ids as $pfids) {
            $filers = ProductFilters::where([["product_id", $pfids['product_id']]])->Select("filter_value")->get()->toArray();
            $all_product_filters_Values_ids = [];
            foreach ($filers as $filer) {
                $all_product_filters_Values_ids[] = $filer['filter_value'];
            }

            $any_dif = array_diff($values,$all_product_filters_Values_ids);
            if(count($any_dif)<=0){
                $products_have_values[] = $pfids['product_id'];
            }


        }

        $products = Product::where("Tb_Products.organization_id",$organization_id)->whereIn("Tb_Products.id",$products_have_values)
            ->join('Tb_Identities', 'Tb_Identities.id', '=', 'Tb_Products.employee_id')
            ->select(
                "Tb_Products.*",
                "Tb_Identities.first_name as fname",
                "Tb_Identities.last_name as lname"
            )
            ->get()->toArray();


        return $products;