kjd*_*n84 2 php laravel eloquent
我正在尝试使用withCount()关系的关系。我得到的错误是Method Illuminate\Database\Query\Builder::forums.threads does not exist.。
鉴于这些模型:
class Category extends Model
{
public function forums()
{
return $this->hasMany('App\Forum');
}
}
class Forum extends Model
{
public function category()
{
return $this->belongsTo('App\Category');
}
public function threads()
{
return $this->hasMany('App\Post')->orderByDesc('created_at');
}
}
Run Code Online (Sandbox Code Playgroud)
在我的控制器中考虑以下内容:
public function index()
{
$categories = Category::with('forums')->withCount('forums.threads')->orderBy('order')->get();
return view('home', compact('categories'));
}
Run Code Online (Sandbox Code Playgroud)
我认为以下内容:
@foreach($categories as $category)
{{ $category->title }}<br>
@foreach($category->forums as $forum)
{{ $forum->title }}<br>
{{ $forum->threads_count }}
@endforeach
@endforeach
Run Code Online (Sandbox Code Playgroud)
我知道我可以简单地withCount从控制器中删除并使用$forum->threads->count(),但是是否可以按我想要的方式查询计数?
如果是这样,如何?我希望通过急切加载计数来尽可能快地加载(threads当然,不加载所有实际的 )。
试试withCount()里面closure:
$categories = Category::with(['forums'=>function($q){
$q->withCount('threads');
}])->orderBy('order')->get();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1488 次 |
| 最近记录: |