jeudi 21 novembre 2019

Laravel: How to get duplicated records and group them together?

The code below is what I have to get all the duplicated products (by title) and group them together. It works perfectly fine. However, I so many records in my Products table and getting all of them causes a performance issue. Is there a way this could be optimised to avoid getting all records and group them in one query? Thank you.

$products = Product::all();

$groupsOfProducts = $products->groupBy('title');

$duplicatedProductsGrouped = [];

foreach($groupsOfProducts as $productGroup) {

    $productIsDuplicated = $productGroup->count() > 1; 

    if($productIsDuplicated) {

        $duplicatedProductsGrouped[] = $productGroup;

    }

}

var_dump($duplicatedProductsGrouped);



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire