【问题标题】:How to join on a select result with eloquent in Laravel?如何以雄辩的方式加入laravel的选择结果?
【发布时间】:2018-09-27 00:23:28
【问题描述】:

我想加入这样的其他选择的结果:

SELECT *
  FROM TABLE1
  JOIN (
  SELECT cat_id FROM TABLE2 where brand_id = 2 GROUP BY TABLE2.cat_id) AS b ON TABLE1.id = b.cat_id

有没有办法用 eloquent 做到这一点?

【问题讨论】:

  • 你的数据模型到底是什么样的?

标签: laravel eloquent


【解决方案1】:

正如here 所说,使用DB:raw() 将解决您的问题。

DB::table('table1')->join(DB::raw("(SELECT 

          cat_id

          FROM table2

          WHERE brand_id = 2   

          GROUP BY table2.cat_id

          ) as b"),function($join){

            $join->on("b.cat_id","=","table1.id");

      })->get();

【讨论】:

  • 如何在这个查询中添加 where brand_id = 2?
  • brand_id 是哪个表的列?表 1 还是表 2?
  • 你知道我怎样才能得到 colloction 或 array 的结果吗?现在我有这样的答案:0 => {#614 ▼ +"id": 184
  • 好吧,你可以像这样添加一个 toArray() 来将结果转换为一个数组。 DB::table('table1')->.................->get()->toArray();
  • 不,我想将 stdclass 转换为集合,到 Array 只给我数组格式的第一级结果,我想在 Collection 或数组中获取所有结果
【解决方案2】:
\DB::table('table1')->join('table2' , function($join){
   $join->on('table1.id', '=', 'table2.cat_id');
})->select(['table2.cat_id' , 'table1.*'])
->where('table2.brand_id' , '=' , '2')
->groupBy('table2.cat_id');

取决于brand_id是在table1还是table2中

您也可以使用模型方法。

TABLE1::join('table2' , function($join){
   $join->on('table1.id', '=', 'table2.cat_id');
})->select(['table2.cat_id' , 'table1.*'])
->where('table2.brand_id' , '=' , '2')
->groupBy('table2.cat_id');

【讨论】:

  • 其实这不是雄辩的(你所谓的“模型方法”),而是查询构建器。
  • 你想和关系一起做吗?
  • 这不是用雄辩的,也没有像询问一样给我答案。
  • 我的答案是 table1 的记录,但这只给了我 table2 中的 cat_id,如下所示:array:2 [▼ 0 => {#615 ▼ +"cat_id": 184 } 1 => {#614 ▼ +"cat_id": 185 } ]
  • 你想和关系一起做吗? @HamidNaghipour
猜你喜欢
  • 2019-01-08
  • 2020-07-29
  • 2023-01-27
  • 2017-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-27
  • 1970-01-01
相关资源
最近更新 更多