php - 如何将我的查询更改为 laravel eloquent ORM?

标签 php mysql laravel eloquent

我有这样的查询:

SELECT 
t1.id as id_guru, t1.nama_guru,
COALESCE(t2.total, 0) AS total
FROM `guru` t1
LEFT JOIN(SELECT id_guru, COUNT(*) as total FROM absensi_guru where status_masuk = "Terlambat" GROUP BY id_guru) t2 ON t1.id = t2.id_guru

我想将我的查询更改为 laravel Eloquent ORM,我从这个网站甚至在 laracast 中尝试了很多方法。

最佳答案

如果我是你,我将使用你拥有的查询在 MySQL 中创建一个 View ,然后使用 Laravel 中的 Eloquent 或查询生成器来查询数据库。

以防万一,如果你想直接在 Laravel 中而不使用 View ,则需要定义 Eloquent 关系。您可以找到更多关于 Eloquent 关系的信息HERE

要在 Laravel 中使用,这里有一个示例代码,只是不要复制粘贴,理解它并更新您的查询

$multipleitems = DB::table('items')
             ->leftJoin('votes','items.itemId','=','votes.masterItemId')
             ->select('items.itemId',DB::raw('ifnull(sum(votes.votes),0) as voteSum'))
                   ->whereBetween('votes.voteDate',array($startDate,$endDate))
                   ->where($condition)
                   ->groupBy('items.temId')
                   ->get();

这是ref

关于php - 如何将我的查询更改为 laravel eloquent ORM?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43541205/

相关文章:

mysql - 获取日期时间从/到特定时间之间的平均计数

javascript - 以 Angular 从 API JSON 中排序的项目日期

php - 使用 PHP 的 odbc 抓取一个 varchar(max) 列

php - 发送带有 php 附件的电子邮件

php - Codeigniter 排序数据

mysql - 获取过去 48 小时的数据 - MySQL

Laravel 望远镜不会删除

javascript - JSON 文件提取自 url

php - 在具有多个索引的 PHP 中使用 Sphinx

php - Laravel 5.1 - 在保存到数据库时生成唯一的 10 个字母数字字符代码