【发布时间】:2021-06-06 21:13:57
【问题描述】:
我在post.blade.php有一个简单的脚本
{{ Auth::user() ? ($post->ratings()->where('user_id', Auth::user()->id)->exists() ? 'You rated ' . $post->userRating($post) : '') : '' }}
在我的post 模型中可以访问的两个函数是:
public function ratings() {
return $this->hasMany(Rating::class);
}
public function userRating(Post $post) {
return $this->ratings()->where([
['post_id', '=', $post->id],
['user_id', '=', Auth::user()->id]
])->first('stars')->stars / 2;
}
这是我postcontroller中的index:
public function index() {
$posts = Post::with('user')->withAvg('ratings', 'stars')->paginate(100);
return view('posts.index', [
'posts' => $posts,
]);
}
然而,这需要大约 1 秒来加载每个页面,因为它必须执行该代码 100 次。
如果我从刀片文件中删除顶部提到的脚本,页面加载速度会更快。
我在原始 MySQL 中进行了这个查询,它加载结果的速度明显更快:
select `posts`.*, (select avg(`ratings`.`stars`) from `ratings` where `posts`.`id` = `ratings`.`post_id`) as `ratings_avg_stars`, (SELECT count(*) FROM ratings WHERE post_id = posts.id and user_id = 1) as rated from `posts` where `posts`.`deleted_at` is null
如果我把它放在我的postcontroller 我认为页面加载速度会更快,我不知道如何将 MySQL 转换为 Eloquent,我尝试了一个查询转换器,但那些卡在子查询上。
如何将 MySQL 查询转换为 Eloquent 查询?
【问题讨论】:
标签: php laravel laravel-blade