简体   繁体   中英

Laravel relationships - are there multiple *unnecessary* database calls?

I have 2 models: Post and User where each Post has one User and each User has many Post s.

User.php:

// User.php

public function posts()
{
    return $this->hasMany(Post::class);
}

Post.php:

// Post.php

public function user()
{
    return $this->hasOne(User::class);
}

I load a post through my PostsController :

// PostsController.php

public function show($id)
{
    $post = Post::find($id);

    return view('posts.show', compact('post'));
}

In the view, I make calls to both the post that I loaded in and to the user related to the post. I make multiple calls to the user object:

// views/posts/show.blade.php

<h1>{{ $post->title }}</h1>
<p>{{ $post->user->name }}</p>
<p>{{ $post->user->email }}</p>

Will these 2 calls to the $post->user resource make 2 calls to the database?

How does the Eloquent relationship work in the back end? Does the relationship always return the entire user object when I get the post object, or does it lazily get the user data?

I am concerned about hosting my database with a provider that charges based on data transferred from the database (GCP) and I don't understand how the Eloquent relationship will call the database.

Laravel provides a feature called Eager Loading which lets you load the model and any relationships by optimizing the queries:

Post::with('user')->find($id);

Eager loading works with many relationships as well. The following would also result in just two queries, regardless of the amount of posts a user has:

User::with('posts')->find($id);

This will load the Post entity's user model so that accessing it will not require a second query. You can read more about eager loading and other performance enhancements in the docs .

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