Conixs
1 week ago

Group all pivot data

Posted 1 week ago by Conixs

Hello everyone, is it possible to group the pivot results of a belongsToMany relationship?

I have the below relationship:

public function tabelaPrecoRel() {
    return $this->belongsToMany(ProductTabPrice::class, 'vw_product_tab_rel', 'product_id', 'tab_id')->withPivot('value', 'value_unit', 'tab_preco_qtd');
  }

And it returns the following information:

{
    "id": 479,
    "pivot": {
        "product_id": 5747,
        "tab_preco_qtd": 479,
        "value": "-60.0000"
    }
},
{
    "id": 479,
    "pivot": {
        "product_id": 5747,
        "tab_preco_qtd": 479,
        "value": "-70.0000"
    }
}

However, I wish to get it grouped as an array without showing the duplicate information.

{
    "id": 479,
    "pivot": [
     {
        "product_id": 5747,
        "tab_preco_qtd": 479,
        "value": "-60.0000"
    },
   {
        "product_id": 5747,
        "tab_preco_qtd": 479,
        "value": "-70.0000"
    }]
}

Please sign in or create an account to participate in this conversation.