你好,我的 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 時另外,DISTINCT 部分在那里什么也不做,請忽略它。我只是想試試
1 回答

精慕HU
TA貢獻1845條經驗 獲得超8個贊
首先,您需要單獨指定選擇列。就像這樣:
->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();
- 1 回答
- 0 關注
- 206 瀏覽
添加回答
舉報
0/150
提交
取消