Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Laravel Blade中使用count()是否效率低下?_Laravel - Fatal编程技术网

在Laravel Blade中使用count()是否效率低下?

在Laravel Blade中使用count()是否效率低下?,laravel,Laravel,这更像是一个“最佳实践”问题 我的网站有文章,文章可以有评论 public function comments() { return $this->hasMany('App\Comment', 'submission_id'); } 在首页列出文章的地方,评论的数量如下所示: @if ($article->comments->count()) {{ $article->comments->count() }} {{ $article-

这更像是一个“最佳实践”问题

我的网站有文章,文章可以有评论

public function comments() {
    return $this->hasMany('App\Comment', 'submission_id');
}   
在首页列出文章的地方,评论的数量如下所示:

@if ($article->comments->count())
    {{ $article->comments->count() }}
    {{ $article->comments->count() == 1 ? 'comment' : 'comments' }}
@endif
我在想,在这个例子中,我的数据库是否因为这个简单的代码片段被查询了3次

每次我通过这个关系获得注释计数时,它是否会加载整个注释数组及其所有列?因为有时文章可以有超过1k+的评论


如果是这样的话,在我的
articles
数据库表中设置一列,每次发布评论时都会增加,然后直接获取,而不是通过关系获取,这不是最佳做法吗。它取决于您何时使用
->count()
,以及它是
集合
版本还是
生成器
版本。请参见以下示例:

示例一-使用
comments()
方法的新查询:

$article = Article::first();
$article->comments()->count();
在本例中,使用
$article->comments()
会启动一个新的查询(使用
Builder
类)。无论您如何完成此查询,即使用
->first()
->get()
->count()
将执行新的查询

现在,示例2-带有
注释的新查询
属性:

$article = Article::first();
$article->comments->count();
$article = Article::with(["comments"])->first();
$article->comments->count();
在本例中,
$article->comments
将执行一个新的查询,因为关系访问器在关系是否已加载时的行为不同。在本例中,它尚未加载,因此
$article->comments
返回一个
Builder
实例,而不是
集合
,因此完成查询将执行一个新查询

最后,示例三-
Collection
access with
comments
property:

$article = Article::first();
$article->comments->count();
$article = Article::with(["comments"])->first();
$article->comments->count();

在最后一个示例中,
$article->comments
已被指定为通过
->with([“comments”])
子句加载,因此它是
集合,而不是
生成器
实例。由于这个原因,调用
->count()
是在使用,并且不会执行额外的查询

我明白了!那很有趣。因此,代替
$submissions=Submission::orderBy('created_at','desc')->paginate(40)我应该做
$submissions=Submission::with([“comments”])->orderBy('created_at','desc')->分页(40)?然而,我有一个问题!由于我的模型中也有
comments
方法,blade如何知道何时执行附加查询以及何时不执行?模型中的
公共函数comments()
指定了关系的工作方式;在你真正使用它之前,它不会起任何作用。但是为了回答您的问题,如果您删除
->count()
方法,并在剩下的部分执行
dd()
,您将看到它是什么,或者是
生成器
或者
集合
。例如:
dd($article->comments())
将始终是
Builder
,而
dd($article->comments)
可以是
Builder
Collection
,这取决于您是否将
->与([“comments”])
一起使用,或者
->加载(“comments”)
,等等。