B
B
BonBon Slick2017-08-09 12:47:52
Laravel
BonBon Slick, 2017-08-09 12:47:52

Laravel Eager Loading vs Joins?

//eager
 $items = UserReport::with(['owner' => function ($query) {
            $query->where('nickname', 'LIKE', '%Test%');
        }, 'reported'])->get();
// 0.14 s
// 4 queries

// joins
 $items = UserReport::where('owner.nickname', 'LIKE', '%Test%')
            ->select('owner.nickname as owner_nickname', 'reported.nickname as reported_nickname',
                'user_report_reasons.reason', 'user_reports.read'  )
            ->leftJoin('users as owner', 'user_reports.from_user_id', '=', 'owner.id')
            ->leftJoin('users as reported', 'user_reports.reported_user_id', '=', 'reported.id')
            ->join('user_report_reasons', 'user_reports.reason_id', '=', 'user_report_reasons.id')
            ->get();
// 0.23 s
// 2 queries

I don’t understand why Eager Loading is faster, although there are more requests. The second option is as clear as the first one for those who understand the framework. However, the second option takes longer to complete and has a lot of code.
What is preferred and why? What will be the performance with 100,000 records or more?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
vism, 2017-08-09
@BonBonSlick

This is the point.
They don’t join, but pull with separate requests.
There are no table join operations, so it works faster.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question