简体   繁体   English

Laravel Eloquent:减少查询数量

[英]Laravel Eloquent: Reduce number of queries

Let's say I have 250 users in users table and each user has one or many books, and each book has one or many chapters. 假设我的users表中有250个用户,每个用户有一本书或多本书,每本书有一个或多个章节。 Now I would like to print the user names, with their book names. 现在,我要打印用户名及其书名。

Controller: 控制器:

$users = User::all();

in blade: 在刀片中:

@foreach($users as $user)
  <tr>
      <td>{{ $user->id }}</td>
      <td>{{ $user->name }}</td>
      <td>
        @foreach($user->books as $book)
          {{ $book->name }},
          @endforeach
      </td>
  </tr>
@endforeach

# of queries 252

Now to overcome the n+1 problem, the query should be 现在要克服n + 1问题,查询应该是

$users = User::with('books')->get();

Now the # of queries are only 2. 现在查询的数量只有2个。

I want to print the book names with number of chapters like this-> BookName(# of chapters). 我想打印带有这样的章节数的书名-> BookName(章节数)。 So in my blade 所以在我的刀片

@foreach($users as $user)
      <tr>
          <td>{{ $user->id }}</td>
          <td>{{ $user->name }}</td>
          <td>
            @foreach($user->books as $book)
              {{ $book->name }} ({{ $book->chapters->count() }}),
              @endforeach
          </td>
      </tr>
    @endforeach

so for 750 books with 1500 chapters the # of queries are about 752 and it increases if chapter number increases. 因此,对于750本书(含1500章),查询数量约为752,如果章节数增加,查询数量也会增加。

Is there any better Eloquent way to reduce it or should I go for raw SQL queries? 有什么更好的Eloquent方式来减少它,还是应该进行原始SQL查询?

From the Eloquent Documentation : 从雄辩的文件

Nested Eager Loading 嵌套的渴望加载

To eager load nested relationships, you may use "dot" syntax. 为了渴望加载嵌套关系,可以使用“点”语法。 For example, let's eager load all of the book's authors and all of the author's personal contacts in one Eloquent statement: 例如,让我们急切地在一项雄辩的陈述中加载本书的所有作者和所有作者的个人联系人:

$books = App\\Book::with('author.contacts')->get();

In your case, you can retrieve the nested relationships you need with the following: 对于您的情况,可以使用以下方法检索所需的嵌套关系:

User::with('books.chapters')->get();

You don't need to load all chapters data and then manually count each collection. 您无需加载所有章节数据,然后手动计算每个集合。 Use withCount() instead: 使用withCount()代替:

$users = User::with('books')->withCount('chapters')->get();

If you want to count the number of results from a relationship without actually loading them you may use the withCount method, which will place a {relation}_count column on your resulting models. 如果您想计算一个关系的结果数而不实际加载它们,则可以使用withCount方法,该方法将在结果模型上放置一个{relation} _count列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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