首先,我很抱歉我糟糕的英语。
我想通过 5 篇文章获得最高浏览量。
我试过了,但 Eloquent 查询有问题。
laravel 源码
<?php
$up = "SELECT id FROM articles WHERE id IN (SELECT id from (SELECT id FROM articles ORDER BY view_count DESC LIMIT 0,5) x)";
$builder = new \App\Article;
$query = $builder->selectRaw("articles.*, $up");
?>
@forelse($query->latest() as $article)
<img src="{{ $article->thumbnail }}" alt="{{ $article->title }}" title="{{ $article->title }}">
@empty
<p class="text-center text-danger">
empty...
</p>
@endforelse
数据库查询结果
MariaDB [test]> SELECT id FROM articles WHERE id IN (SELECT id from (SELECT id FROM articles ORDER BY view_count DESC LIMIT 0,5) x);
+------+
| id |
+------+
| 4018 |
| 4045 |
| 3800 |
| 4011 |
| 4005 |
+------+
5 rows in set (0.00 sec)
我看过关于这个主题的其他帖子,但我没有得到解决方案。
感谢您的帮助。
最佳答案
首先,您必须在 Controller 中使用您的服务 sttuf 来清理 View 并遵守 MVC 模式。
所以在 Controller 中你可以使用 Eloquent 来做到这一点:
$articles = App\Article::orderBy('view_count', 'desc')
->take(5)
->get();
return view('SomeView')->withArticles($articles);
在 SomeView.blade.php
中:
@forelse($articles as $article)
<img src="{{ $article->thumbnail }}" alt="{{ $article->title }}" title="{{ $article->title }}">
@empty
<p class="text-center text-danger">
empty...
</p>
@endforelse
关于php - Laravel5 Eloquent : How to get a few articles from special condition?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47303656/