Laravel Eloquent Lazy Eager 加载计数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40019683/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel Eloquent Lazy Eager Load Count
提问by edlouth
I'm ideally looking for a function like
我理想地寻找像这样的功能
load('relationship')
but which loads a count in the same way
但以相同的方式加载计数
withCount('relationship')
works for eager loading.
适用于急切加载。
I'm thinking it is going to be called loadCount('relationship')
我想它会被调用 loadCount('relationship')
采纳答案by Maksim Ivanov
回答by rzb
As of Laravel 5.2, this functionality is built-in.
从 Laravel 5.2 开始,这个功能是内置的。
Provided you have a hasMany relationship between Post and Comment, do:
如果您在 Post 和 Comment 之间有 hasMany 关系,请执行以下操作:
<?php
$posts = App\Post::withCount('comments')->get();
foreach ($posts as $post) {
echo $post->comments_count;
}
You can even eager load relationships count by default by declaring this in your model:
你甚至可以通过在你的模型中声明这个默认情况下预先加载关系计数:
<?php
// Post model
protected $withCount = ['comments'];
回答by hubrik
This solutionworks great for me:
这个解决方案对我很有用:
Create a new hasOne relationship on the related model and add a raw select to the query for the count. For example, if you want to eager load the number of tasks for a given user, add this to the User Model:
在相关模型上创建一个新的 hasOne 关系,并将原始选择添加到计数的查询中。例如,如果您想预先加载给定用户的任务数量,请将其添加到用户模型中:
public function taskCount()
{
return $this->hasOne('App\Task')
->selectRaw('user_id, count(*) as count)
->groupBy('user_id');
}
And then eager load the count like this:
然后像这样急切加载计数:
$user = User::where('email', $email)->with('taskCount)->first();
And access the count like this:
并像这样访问计数:
$taskCount = $user->task_count->count;