简体   繁体   中英

how to change my query into laravel eloquent ORM?

i have query like this :

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

and i want to change my query into laravel Eloquent ORM, i tried so many way from this site and even in laracast.

If I was you, I will create a View in MySQL with the Query you have and then use Eloquent or Query Builder in Laravel to query the DB.

In case, If you want directly in Laravel, without view, you need to define Eloquent relationships. You may find more information about eloquent relationships HERE

To use in Laravel, here is an example code, just do not do copy-paste, understand it and update your query

$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();

Here is the ref

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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