【问题标题】:Group_concat - laravel eloquentGroup_concat - laravel 雄辩
【发布时间】:2014-11-08 23:04:32
【问题描述】:

请在使用 eloquent 而不是原始查询的查询中使用 group_concat。

这是我尝试执行但对我不起作用的代码:

commands::join('products', 'products.id', '=','commands.idproduct')
->select('commands.username','**group_concat(products.name)**')
->group by ('commands. username')
->get();

提前致谢:)

【问题讨论】:

  • 尝试使用 DB::raw() 在查询中包装你想要的“原始”SQL:->select('commands.username',DB::raw('group_concat(products.name)'))
  • 感谢您的回复@alexrussell,但问题是当我添加 DB::raw 并再次运行应用程序时,我收到此错误:Symfony \ Component \ Debug \ Exception \ FatalErrorException Class 'Storage \Commands\DB' 未找到
  • 啊,您在命名空间中 - 在命名空间声明后添加 use DB; 或在代码中使用 DB\DB::raw('group_concat(products.name)')
  • 非常感谢@alexrussell,现在我添加了使用数据库;而且效果很好:)

标签: laravel eloquent group-concat


【解决方案1】:

我刚用过:

use DB;

在我的查询中我使用了

DB::raw('group_concat(products.name)')

【讨论】:

  • 您应该将此答案标记为正确答案,以便人们知道。
【解决方案2】:

最好的例子..

ModelName::select('ID', DB::raw('CONCAT(First_Name, " ", Last_Name) AS full_name')) ->获取() ->toArray(); 结果 乔恩·多伊,杰弗里·韦,泰勒,泰勒·奥特维尔

【讨论】:

    【解决方案3】:

    这对我有用

    $list = TableName::where('user_id', 'user_001'
            ->groupBy('user_id')
            ->groupBy('subscription_id')
            ->select('user_id','subscription_id','type')
            ->selectRaw('GROUP_CONCAT(holiday) as holidays')
            ->get();
    

    use Illuminate\Support\Facades\DB;
    
    $sql = 'SELECT GROUP_CONCAT(holiday) as holidays, user_id,subscription_id, type FROM TableName 
            where vendor_id = 'user_001' GROUP BY user_id, subscription_id;';
    $list = DB::select($sql, []);
    

    【讨论】:

      【解决方案4】:

      或者直接替换

      ->select('commands.username','**group_concat(products.name)**')
      

      ->selectRaw('commands.username, **group_concat(products.name)**')
      

      【讨论】:

        【解决方案5】:

        这对我有用:(9.0+)

        DB::raw('string_agg(products.name, \',\') as products')
        

        您需要使用 Illuminate\Support\Facades\DB;为此。

        【讨论】:

          【解决方案6】:

          $data=\DB::table('paging_config') ->leftjoin('paging_groups', 'paging_config.page_group', '=', 'paging_groups.page_number') ->leftjoin('spk_mnt', 'paging_groups.ext', '=', 'spk_mnt.stn_no') ->选择('paging_config.page_group','paging_groups.ext','spk_mnt.stn_status') ->selectRaw('GROUP_CONCAT(DISTINCT 描述) 作为描述') ->where('paging_config.page_group','=','paging_config.page_group') ->groupBy('paging_config.description')

                  ->get();
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2023-03-11
            • 2022-07-25
            • 2016-09-28
            • 2016-05-08
            • 2021-07-03
            • 2021-08-11
            相关资源
            最近更新 更多