我是这样处理的
class CategoriesController extends Controller
{
public function show(Category $category)
{
// 读取分类 ID 关联的话题,并按每 20 条分页
$topics = Topic::with('user', 'category')->where('category_id', $category->id)->paginate(20);
// 传参变量话题和分类到模板中
return view('topics.index', compact('topics', 'category'));
}
}
我是这样处理的
class CategoriesController extends Controller
{
public function show(Category $category)
{
// 读取分类 ID 关联的话题,并按每 20 条分页
$topics = Topic::with('user', 'category')->where('category_id', $category->id)->paginate(20);
// 传参变量话题和分类到模板中
return view('topics.index', compact('topics', 'category'));
}
}
延迟加载
$topics = Topic::where('category_id', $category->id)->paginate(20);
$topics->load(['user', 'category']);
//CategoriesController:
$topics = Topic::where('category_id', $category->id)->with('user'')->paginate(20);
//topics._topic_list.blade.php:
@foreach ($topics as $topic)
@php($category ?? $category = $topic->category)
category默认的查询实例直接拿来用,由于和topics.index共用模板,所以再加个判断就行。
虽然只是多一次根据主键的in查询,但php效率比mysql快多了,orm是长连接复用,但分析器,优化器,调用存储引擎接口还得走一遍。
能少查就少查吧,个人愚见。
推荐文章: