【问题标题】:Laravel5 Eloquent: How to get a few articles from special condition?Laravel5 Eloquent:如何从特殊条件下获取几篇文章?
【发布时间】:2017-11-15 09:27:54
【问题描述】:

首先,对不起我的英语不好。
我想用 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)

我已经看过有关此主题的其他帖子,但我没有得到解决方案。
感谢您的帮助。

【问题讨论】:

标签: php mysql laravel relationship laravel-eloquent


【解决方案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

【讨论】:

    【解决方案2】:

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

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

    在您的文章.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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-17
      • 2015-06-26
      • 2021-06-14
      • 1970-01-01
      • 2017-03-29
      • 2018-09-07
      • 1970-01-01
      相关资源
      最近更新 更多