N
N
ne-programmist2022-02-22 17:08:43
Laravel
ne-programmist, 2022-02-22 17:08:43

Why doesn't distinct work in query builder?

Tell me why distinct does not work in query builder? We need to get records with a unique value categories.name

There is a query like this:

$subCategories = DB::table('categories')
            ->select(
                'categories.parent_category_id',
                'categories.name',
                'categories.has_subcategories',
                'user_categories.user_id'
            )
            ->leftJoin('user_categories', 'categories.id', '=', 'user_categories.category_id')
            ->where('parent_category_id', $id)
            ->distinct()
            ->get()
            ->toArray();


Result:
"subCategories": [
            {
                "parent_category_id": 1,
                "name": "Mac",
                "has_subcategories": 0,
                "user_id": 148
            },
            {
                "parent_category_id": 1,
                "name": "Mac",
                "has_subcategories": 0,
                "user_id": 149
            },
            {
                "parent_category_id": 1,
                "name": "Mac",
                "has_subcategories": 0,
                "user_id": 151
            }
        ]


And it should be:
"subCategories": [
            {
                "parent_category_id": 1,
                "name": "Mac",
                "has_subcategories": 0,
                "user_id": 148
            }
        ]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Anton, 2022-02-22
@ne-programmist

Because distinct works on a combination of all selectable fields, and here the user_id is different

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question