SPQRInc
SPQRInc

Reputation: 188

hasMany with additional information

I'd like to get the following working:

I got a UserGroup that should have discounts on a list of ProductGroups.

Example:

UserGroup

{
    "data": {
        "id": 2,
        "title": "Test",
        "discounts": null,
    }
}

ProductGroups

{
  "data": [
    {
      "id": 1,
      "title": "Group1"
    },
    {
      "id": 2,
      "title": "Group2"
    }
  ]
}

Expected result

UserGroup

{
  "data": {
    "id": 2,
    "title": "Test",
    "discounts": [
      {
        "productgroup_id": 1,
        "discount": 0
      },
      {
        "productgroup_id": 2,
        "discount": 10
      }
    ]
  }
}

So now I'd like to know: How to save this the best? First I thought about JSON. The problem: If the ProductGroup is being deleted, the UserGroup-discounts-JSON is not updated using a cascade.

Upvotes: 1

Views: 65

Answers (1)

Mike
Mike

Reputation: 862

You could add a pivot table user_group_product_groups with the columns user_group_id, product_groups_id and discount

In your ProductGroup model add

public function userGroups(){
    return $this->belongsToMany(UserGroup::class)->withPivot('discount');
}

In your UserGroup model add

public function productGroups(){
    return $this->belongsToMany(ProductGroup::class)->withPivot('discount');
}

You can now use $productGroup->userGroups and it wil include the discount from the pivot table.

Or use $userGroup->productGroups and it wil include the discount from the pivot table.

Upvotes: 3

Related Questions