menu

Questions & Answers

How to group attribute values?

How to get this result:

foreach ($products as $product) {
    $product->name

    foreach ($product->attributes as $attribute) {
        $attribute->name

        foreach ($attribute->values as $value) {
            $value->name
        }
    }
}

And

{
    "name": "Product",
    "attributes": [
        {
            "name": "Attribute 1",
            "values": [
                "name": "Value 1",
                "name": "Value 2",
            ]
        }
    ]
}

Instead of this:

foreach ($products as $product) {
    $product->name

    foreach ($product->attributeValues as $attributeValue) {
        $attributeValue->attribute->name
        $attributeValue->name
    }
}

And

{
    "name": "Product",
    "attribute_values": [
        {
            "attribute_name": "Attribute 1",
            "value_name": "Value 1",
        },
        {
            "attribute_name": "Attribute 1",
            "value_name": "Value 2",
        }
    ]
}

Database

products
--- id
--- name

attributes
--- id
--- name

attribute_values
--- id
--- attribute_id
--- name

attribute_value_product
--- id
--- attribute_value_id
--- product_id

Products

  • Many-to-Many relationship for Attribute Values.

Attributes

  • One-to-Many relationship for Attribute Values.

Attribute Values

  • One-to-Many (Belongs To) relationship for Attributes.
  • Many-to-Many relationship for Products.

I'm struggling to find solution but failed so i posted here for get some solution.

Please help me.

Comments:
2023-01-23 23:30:09
A tip: never use a many-tomany relationship, best practice is to create a bridging table. Check out this post why: stackoverflow.com/questions/7339143/…
2023-01-23 23:30:09
you can accomplish this using eloquent constrain egear loadingwith, select, groupBy instead of having 3 foreach
2023-01-23 23:30:09
@silver Can you show an example?
2023-01-23 23:30:09
@Nemoko How would you solve this problem?
Answers(0) :