Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

KikoLdasd's avatar

How to group values from database by id

Hi, how can I group some data as follows I have this datas:

   {
            "category_id": 43,
            "attribute_id": 11
        },
        {
            "category_id": 44,
            "attribute_id": 11
        },
        {
            "category_id": 45,
            "attribute_id": 11
        },
        {
            "category_id": 46,
            "attribute_id": 11
        },

I would like to group the data as follows { attribute_id:11, categories: { category_id: 45, category_id, 46 } } How can I do this? I tried to give a groupBy but this will not work Is there a way?

CategoryFiltrableAttribute::query()->where('attribute_id', 11)->with('childs')->get();
public function childs()
    {
        return $this->hasMany(CategoryFiltrableAttribute::class, 'attribute_id');
    }
0 likes
1 reply

Please or to participate in this conversation.