【问题标题】:how to convert Query Builder to Elequent query?如何将查询生成器转换为 Eloquent 查询?
【发布时间】:2021-10-14 03:35:53
【问题描述】:

我有来自查询生成器的代码,我想将其转换为 eloquent,但它不起作用

我的查询生成器代码

$topkabupatens =  DB::table('sekolahs as S')
        ->select('K.name', DB::raw('count(S.kabupaten) as jumlah_kabupaten'))
        ->join('kabupaten_kotas as K', 'S.kabupaten', '=', 'K.id')>orderBy('jumlah_kabupaten', 'DESC')->groupBy('K.name')->limit(10)->get();

我的查询生成器代码

$topkabupatens = Sekolah::with('kabupaten')->withCount('kabupaten')>orderBy('kabupaten_count', 'DESC')->groupBy('name')->limit(10)->get();

我的错误在哪里?

我的查询生成器代码运行但没有 eloquent

【问题讨论】:

  • 请注意,with('kabupaten') 执行连接的方式与 ->join() 不同。此外,)>orderBy(...) 是语法错误;缺少该箭头中的-)->orderBy(...)
  • $topkabupatens = Sekolah::with('kabupaten')->withCount('kabupaten')->orderBy('kabupaten_count', 'DESC') ->groupBy('name')->限制(10)->获取();我修复了它,但它仍然是一个问题
  • 我认为这是一个错字,但最好确定一下。你能更好地描述你的问题吗? “它不起作用”不是一个很好的描述......

标签: laravel eloquent laravel-query-builder


【解决方案1】:

试试

$topkabupatens = Sekolah::select('kabupaten_kotas.name')->withCount('kabupaten_kotas.kabupaten')
                ->leftjoin('kabupaten_kotas', 'Sekolah.kabupaten', '=', 'kabupaten_kotas.id')
                ->orderBy('kabupaten_count', 'DESC')
                ->groupBy('name')
                ->limit(10)
                ->get();

【讨论】:

    猜你喜欢
    • 2015-07-21
    • 1970-01-01
    • 2020-10-13
    • 2020-07-09
    • 2018-08-06
    • 1970-01-01
    • 2019-06-21
    • 1970-01-01
    • 2015-12-13
    相关资源
    最近更新 更多