lundi 25 mai 2020

GroupBy On OneToMany Relationship (Laravel 5.8)

I have the following chunk of code which returns data successfully:

ProductAttributeKey::withAndWhereHas('product_attribute_values', function($query) use ($organization_id, $country_id) {
    $query->whereHas('product', function ($query) use ($organization_id, $country_id) {
        $query->whereHas('organization_price_matrix', function ($query) use ($organization_id, $country_id) {
            $query->where('organization_id', $organization_id)
                ->where('product_cost_matrix.country_id', $country_id);
       });
   }); /* Tested Here: ->grouBy("name") */
})
->orderBy($order_by, $sort_by)
->paginate($per_page)

The data comes back in the following format when returned in a resource:

enter image description here

I want to group by the attribute "name" in the array "product_attribute_values".

I have tested groupBy name as you can see in the code block at the top. This seems works fine when the array for "product_attribute_values" contains more than one value, but if it contains one value it seems to remove it.

With groupBy("name"):

enter image description here

As you can see, it works fine for the first value "Alcohol Volume", but on the next value, "Batteries Included", it removes the only value in the array "product_attribute_values". I don't want it to remove that single value.

How would this be fixed?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire