首页 > 解决方案 > Laravel How Make DB raw can inside function

问题描述

我在 laravel 上有问题。我想用 eloquent 显示百分比,但返回空值

这是我的控制器

  $group_categories = Proyek::with(['modul' => function($query){
        $query->select(DB::raw('((select count(*) from modul where status = 0 and deleted_at IS NULL) / 
                      (select count(*) from modul where deleted_at IS NULL)) * 
                        100 as count' ));
    }])->get();

这是 Json 返回

{
id: "10",
proyek: "JuZka",
created_at: "2018-08-12 01:54:04",
updated_at: "2018-09-23 05:49:13",
modul: [ ]
},

标签: mysqlsqllaravellaravel-query-builder

解决方案


你可以使用这样的代码:

$all_models = (new Proyek)->count();
$models = (new Proyek)->where('status', 0)->count();
$percentage = $models / $all_models * 100;
$group_categories = Proyek::wheere('modul', $percentage);

推荐阅读