DarkCode999
DarkCode999

Reputation: 182

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.

Upvotes: 0

Views: 778

Answers (1)

Qammar Feroz
Qammar Feroz

Reputation: 718

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

Upvotes: 1

Related Questions