在 laravel 中使用 .each() 时如何过滤集合行?

How to filter collection rows while using .each() in laravel?

我想过滤这个 $authors 集合。

$authors = Author::get();

在我看来,我需要显示一个作者有多少本书是相关的。
我使用 .each() 将 count 合并到 $authors 并将 return 合并到它被调用的位置。

return $authors->each(function($author, $key){

            $author->count = Author::findOrFail($author->id)->books()->count();

        });

问题是"How can I remove/filter if an author have not wrriten any of a book(count <= 0)?"

我试过了,但失败了。

return $authors->each(function($author, $key){

                $author->count = Author::findOrFail($author->id)->books()->count();
               $author->filter(function($author, $key){
                    return $author->count <= 0;
               })

            });

你应该使用withCount() to avoid N+1和性能问题:

$authors = Author::withCount('books')->get();

在 Blade 视图中,您可以执行以下操作:

$author->books_count

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.

https://laravel.com/docs/5.4/eloquent-relationships#counting-related-models