php - Laravel5 Eloquent : How to get a few articles from special condition?

标签 php mysql laravel relationship eloquent

首先,我很抱歉我糟糕的英语。
我想通过 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/

相关文章:

php - Doctrine 2.5 意外的关联获取行为 [Symfony 3]

php - 插入具有相同唯一 ID 的多行

php - PHP 和 MySQL 中 undefined variable 索引

php - Laravel 4.1 _token 表单提交错误

PHP DDD如何命名入口点方法?

php - WordPress 数据库和查询

mysql - 使用 CASE 的条件内部连接

php - 如何检查 Laravel 命令是否仍在运行?

php - Laravel 5.6升级后Redis "Error while reading line from the server."

php - 如何从数据库获取两组结果 - 拥有某个项目的用户以及拥有该项目的用户的 friend