简体   繁体   English

此查询替换为 Laravel。 在laravel中怎么写?

[英]This query replace to Laravel. How to write in laravel?

select u.name,GROUP_CONCAT( DISTINCT c.category_name SEPARATOR ',') AS category_name FROM users as u 
INNER JOIN category as c ON FIND_IN_SET(c.id, u.cate) 
GROUP BY u.id
 User::with('category'=>function($q){
     $q->select( DB::raw("GROUP_CONCAT( DISTINCT c.category_name SEPARATOR ',') AS category_name"))->whereRaw("find_in_set(c.id, user.cate)")
    })->groupBy("user.id")->get();

or you can simply use for any query you have或者您可以简单地用于您拥有的任何查询

DB::select( DB::raw("select u.name,GROUP_CONCAT( DISTINCT c.category_name SEPARATOR ',') AS category_name FROM users as u 
INNER JOIN category as c ON FIND_IN_SET(c.id, u.cate) 
GROUP BY u.id));

With query builder you can do It un this way使用查询构建器,您可以这样做

$data = User::select('users.name')
             ->selectRaw("GROUP_CONCAT( DISTINCT category.category_name SEPARATOR ',') AS category_name")
             ->join('category', 'category.id', '=', 'users.cate')
             ->groupBy('users.name')
             ->get();

Use:用:

  • selectRaw for running pure sql queries selectRaw用于运行纯 sql 查询
  • Use innerJoin to link two tables使用innerJoin链接两个表
  • Use groupBy for grouping results this because you're using GROUP_CONCAT使用groupBy对结果进行分组,因为您使用的是GROUP_CONCAT
  • In spite of using table users name i do prefer yo invoke the model name related to It尽管使用表用户名,我更喜欢调用与它相关的模型名称
  • Only check in my example table AND column names只检查我的示例表和列名

Another option use Laravel relationships but for this you will need另一种选择使用 Laravel 关系,但为此您需要

  • Model for every table每个表的模型
  • belongsTo and hasMany methods created ay your model classes belongsTohasMany方法创建了你的模型类

Also Is neccesary you keep in mind还需要记住吗

You need to GROUP BY for every column in your SELECT statment because:您需要对SELECT语句中的每一列进行GROUP BY ,因为:

  • It's part of standar这是标准的一部分
  • Laravel comes with strict mode enabled Laravel 启用了严格模式
  • Except MySQL, every SQL engine Will throw an error if you dont do this除了 MySQL,如果你不这样做,每个 SQL 引擎都会抛出错误
  • Here the MySQL docs. 这里是 MySQL 文档。 where you can read more about it, because your group is wrong你可以在那里阅读更多关于它的信息,因为你的group错了

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM