foreach in select eloquen in laravel?

In controller :

    $productId = 1;
    $productNew = 1;
    $productHot = 2;
    $productDefective = 3;
    
    $product = Product::select('product_type', DB::raw('count(*) as total'), DB::raw("DATE_FORMAT(created_at, '%Y-%m-%d') as date"),
                    DB::raw('SUM(product_type = ' . $productNew . ') as productNew'), 
                    DB::raw('SUM(product_type = ' . $productHot . ') as productHot'),
                    DB::raw('SUM(product_type = ' . $productDefective . ') as productDefective'))
                    ->where('product_id', $productId)->groupBy('date', 'product_type')->get()->toArray();

Now I want to create a foreach loop in select, can I?

Eg:

$productType = [
   'productNew' => 1,
   'productHot' => 2,
   'productDefective' => 3
];
foreach ($productType as $key => $type) {
   DB::raw('SUM(product_type = ' . $type . ') as '.$key.');
}

Give me any ideas.Thanks

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can use addSelect() to add columns to your query:

$query = Product::where('product_id', $productId)->groupBy('date', 'product_type');

$productType = [
   'productNew' => 1,
   'productHot' => 2,
   'productDefective' => 3
];
foreach ($productType as $key => $type) {
    $query->addSelect(DB::raw('SUM(product_type = ' . $type . ') as ' . $key));
}

$result = $query->get()->toArray();


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x