Answer the question
In order to leave comments, you need to log in
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();
"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
}
]
"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
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 questionAsk a Question
731 491 924 answers to any question