简体   繁体   中英

Why do I need use 'with' in Laravel Eloquent?

First of all, sorry for my bad English.

I have Eloquent query

$gigs = Gig::active()
        ->plusGigs()
        ->with('member')
        ->paginate(16);

and I have with function in my model

public function member()
{
    return $this->belongsTo('App\User', 'USERID', 'USERID')
        ->select(array(
            'USERID',
            'username'
    ))
}

when I try to use on my view file

{{ $gig->member->username }}

yeah. It works but if I don't use ' with('member') ' in my Eloquent query

it still work {{ $gig->member->username }}

Why do I need to use ' with ' in my Eloquent?

Thanks.

When you use with , laravel knows to pre-fetch the associated members for the gigs as well, in two queries instead of several more. This is known as Eager Loading .

So, the query sounds something like, "Get all gigs for the database." "Get the members for all of these gigs."

All this in only two queries.

If you run it without using the with keyword, laravel needs to hit a new database query each time you do {{ $gig->member->username }} for each gig. This is known as the (n+1) problem . Because, you need (n+1) new queries to get the relevant data from the database ('n' being the number of gigs in your case.)

In this case the query sounds like, "Get all the gigs."

Then, when you are looping through the gigs each time the query sounds like,

"Get the member for gig 1"

"Get the member for gig 2"

"Get the member for gig n"

Since database queries are an expensive load on the server and cause time delays, you will want to minimise these as much as possible. The time delay may be negligible for small number of items, but it's always good to follow best practises.

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