I am new to Laravel, can anyone help me with this how should I get unique records through this query in laravel query builder?
as of now, I'm getting duplicate records for example red, pink, red, pink, green
here is my query
MySQL query:
select count(*) as aggregate from (select `product`.`id`, `name`, `category`.`category`, group_concat(product_synonyms.product_synonym)as product_synonym, group_concat(product_tags.product_tag) as product_tag from `product` left join `product_tags` on `product`.`id` = `product_tags`.`product_id` left join `category` on `category`.`id` = `product`.`category_id` left join `product_synonyms` on `product`.`id` = `product_synonyms`.`product_id` where `user_id` = 1 and `product`.`deleted_at` is null group by `product_tags`.`product_id`) as `aggregate_table`;
Query builder:
Product::leftJoin('product_tags', 'product.id', 'product_tags.product_id')
->leftJoin('category', 'category.id', 'product.category_id')
->leftJoin('product_synonyms', 'product.id', 'product_synonyms.product_id')
->where('user_id', auth()->user()->id)
->select('product.id', 'name','category.category',DB::raw('group_concat(product_synonyms.product_synonym)as product_synonym'),DB::raw('group_concat(product_tags.product_tag)) as product_tag')
->groupBy('product_tags.product_id')
->orderBy('product.name', 'ASC')
->paginate(10);
I tried with different join and did many changes, seem I missing something and I couldn't figure it out, and ending with expecting something from a helping hand
For get only one result in your query you need use:
$productDetails = Product::leftJoin('product_tags', 'product.id', 'product_tags.product_id')
->leftJoin('category', 'category.id', 'product.category_id')
->leftJoin('product_synonyms', 'product.id', 'product_synonyms.product_id')
->where('user_id', auth()->user()->id)
->select('product.id', 'name','category.category',DB::raw('group_concat(product_synonyms.product_synonym)as product_synonym')**->first();**
for example.
Paginate if you need more result of query. If you need more than one result use ->get()
You can try this
Product::leftJoin('product_tags', 'product.id', 'product_tags.product_id')
->leftJoin('category', 'category.id', 'product.category_id')
->leftJoin('product_synonyms', 'product.id', 'product_synonyms.product_id')
->where('user_id', auth()->user()->id)
->select('product.id', 'name','category.category',DB::raw('group_concat(product_synonyms.product_synonym)as product_synonym'),DB::raw('group_concat(product_tags.product_tag)) as product_tag')
->distinct()
->groupBy('product_tags.product_id')
->orderBy('product.name', 'ASC')
->paginate(10);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.