jeudi 16 juillet 2020

Laravel - How can I group the collection by a key from a pivot table? (belongsToMany)

I have the following Table structure:

**service**:
id,
name,
...

**product**:
id,
title,
...

**product_services**
id,
service_id,
product_id,
includes_it

I've created a belongsToMany relation, which would give me this output for example:

 {
          "id": 4,
          "...",
          "services": [
            {
              "id": 1,
              "name": "xxxx",
              "pivot": {
                "product_id": 4,
                "service_id": 1,
                "includes_it": 0
              }
            },
            {
              "id": 2,
              "name": "yyy",
              "pivot": {
                "product_id": 4,
                "service_id": 2,
                "includes_it": 1
              }
            },
            {
              "id": 3,
              "name": "zzz",
              "pivot": {
                "product_id": 4,
                "service_id": 3,
                "includes_it": 1
              }
            }
          ]
},  

Each product, has services, which includes it or not.

Now I want my collection output to be grouped by "includes_it". Which comes from the pivot table (pivot.includes_it). If possible, grouped by "true" and "false". Desired output would be:

{
          "id": 4,
          "...",
          "services": [
             "false": [
                 {
                 "id": 1,
                 "name": "xxxx",
                 "pivot": {
                   "product_id": 4,
                   "service_id": 1,
                   "includes_it": 0
                  }
              ],
              "true": [
                 {
                 "id": 2,
                 "name": "yyy",
                 "pivot": {
                   "product_id": 4,
                   "service_id": 2,
                   "includes_it": 1
                 }
                 {
                 "id": 3,
                 "name": "zzz",
                 "pivot": {
                   "product_id": 4,
                   "service_id": 3,
                   "includes_it": 1
                 }
            ]
          ]
}, 

So the "services" where includes_it is 0, will be in the false array and when includes_it is 1, they should be in a true array.

But I'm wasn't really able to do it.

model method:

public function services()
    {
        return $this->belongsToMany('App\Service', 'product_services', 'product_id', 'service_id')
            ->withPivot('includes_it');
    }

I tried things out like adding: "groupBy('product_services.pivot.includes_it') or something. But I only run into errors. Someone an idea?

Using Laravel 6/MySQL.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire