vendredi 28 avril 2017

Eloquent relationship grouped by pivot relationship

I am trying to create a relationship for a model for an Order which will group items by their menu item, to end up with the following data structure (when outputted to JSON):

{
  "id": 123,
  "items": [
    {
      "menu_item_id": 32,
      "items": [
        {
          "id": 456,
          "order_id": 123,
          "menu_item_id": 32
        },
        {
          "id": 457,
          "order_id": 123,
          "menu_item_id": 32
        }
      ]
    },
    {
      "menu_item_id": 37,
      "items": [
        {
          "id": 466,
          "order_id": 123,
          "menu_item_id": 37
        },
        {
          "id": 467,
          "order_id": 123,
          "menu_item_id": 37
        }
      ]
    }
  ]
}

I have the following models & relationships:

class Order extends Model
{
    ...
    public function items()
    {
        return $this->hasMany('App\Models\OrderItem');
    }
    ...
}

class OrderItem extends Model
{
    ...
    public function menuItem()
    {
        return $this->belongsTo('App\Models\MenuItem');
    }
    ...
}

Any suggestions on how?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire