Hekmat
Hekmat

Reputation: 1921

how to sum multiple sql queries in laravel?

how can i sum multiple queries and send them to blade file? i have a query and retrieve the "preferencesProducts" from database, so according to them, i need to retrieve the products too. this is my controller code:

$preferences = DB::table('preferences')->where('customerId', $req->id)->get();

so according to "preference" of above query, i should retrieve another data to, so i make a foreach to extract the $preferencesProducts and then write my query and saving it to a variable called $preferences

            foreach($preferences as $preference)
            {
                $preferencesedProducts= $preferencesedProducts.DB::table('products')->where('productsubCategory', $preference->preference)->get();
            }

as it going into a loop, it makes multiple queries, so how can i sum and send them to blade file?

my code:

return view('/customers/customerHome')->with('preferencesedProducts', $preferencesedProducts);

Upvotes: 0

Views: 51

Answers (1)

DevK
DevK

Reputation: 9942

You can use pluck on the result of preferences query to get an array of preferences and query the products with whereIn:

$preferences = DB::table('preferences')->where('customerId', $req->id)->get();

$preferencesedProducts = DB::table('products')->whereIn('productsubCategory', $preferences->pluck('preference'))->get();

Upvotes: 1

Related Questions