在 Laravel 中调用其他列时,带有 group_concat 的 Select 语句不起作用

你好,我的 Laravel 代码是


$productDetails = DB::table('products')

        ->select(DB::raw('products.name, GROUP_CONCAT(sizes.name) as sizesName'))

        ->join('subcategories', 'products.subcategories_id', '=', 'subcategories.id')

        ->join('size_categories', 'subcategories.categories_id', '=', 'size_categories.categories_id')

        ->join('sizes',function($join){

            $join->on(DB::raw("FIND_IN_SET(sizes.id, size_categories.size_id)"),">",DB::raw("'0'"));

         })

        ->where('products.id', $request->id)

        ->get();

当我使用时,这不起作用,products.name or any other column name in select statement 但是当我在 Db::raw 中仅使用 group_concat 而没有其他任何东西时,查询有效。那么我如何获取其他列呢?请帮忙。我被困了很长一段时间我想要的查询是


select GROUP_CONCAT(sizes.name),`products`.`name`, `products`.`image`, `products`.`id`, `products`.`image_second`, `products`.`description`, `products`.`min_order`, `size_categories`.`size_id` from `products` 

inner join `subcategories` on `products`.`subcategories_id` = `subcategories`.`id`

 inner join `size_categories` on `subcategories`.`categories_id` = `size_categories`.`categories_id`

 join sizes on (FIND_IN_SET(sizes.id,size_categories.size_id)>0) where `products`.`id` = '7'

请注意,上述查询工作正常。我只是无法在 Laravel 中工作。只有 group_concat 部分。


这是我的数据库的屏幕截图,当我不使用 group_concat 时

https://img.mukewang.com/64e9c8120001f48213640762.jpg

另外,DISTINCT 部分在那里什么也不做,请忽略它。我只是想试试

蛊毒传说
浏览 114回答 1
1回答

精慕HU

首先,您需要单独指定选择列。就像这样:->select(DB::raw('products.name'), DB::raw('GROUP_CONCAT(sizes.name) as sizesName'))接下来,由于 group concat 是聚合列,因此您需要对尺寸和产品名称进行分组,因为它位于选择列表中并且与尺寸无关。->groupBy('size_categories.size_id', 'products.id') //edit after your comment. group by prodcuts.id to be able to select columns from products table.所以你的最终查询应该如下所示:$productDetails = DB::table('products')         ->select(DB::raw('products.name'), DB::raw('GROUP_CONCAT(sizes.name) as sizesName'))         ->join('subcategories', 'products.subcategories_id', '=', 'subcategories.id')         ->join('size_categories', 'subcategories.categories_id', '=', 'size_categories.categories_id')         ->join('sizes',function($join){                     $join->on(DB::raw("FIND_IN_SET(sizes.id, size_categories.size_id)"),">",DB::raw("'0'"));          })         ->where('products.id', 7)         ->groupBy('size_categories.size_id', 'products.id')         ->get();
打开App,查看更多内容
随时随地看视频慕课网APP