Laravel5 Eloquent:如何从特殊条件中获取一些文章?

时间:2017-11-15 09:27:54

标签: php mysql laravel relationship laravel-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)

我已经看过关于这个主题的其他帖子,但我没有得到解决方案 谢谢你的帮助。

2 个答案:

答案 0 :(得分:1)

首先,您必须在控制器中使用服务sttuf来清理视图并尊重MVC模式。

所以在控制器中你可以使用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

答案 1 :(得分:0)

按照您只需要在控制器中编写的视图排序的5篇文章:

$articles = Article::orderBy('views', DESC)->take(5)->get();
return view('article', ['articles' => $articles
]);

在你的article.blade.php中:

@forelse($articles() as $article)
    <img src="{{ $article->thumbnail }}" alt="{{ $article->title }}" title="{{ $article->title }}">
@forelse
    <p class="text-center text-danger">
    empty...
    </p>
@endforelese