Laravel Eloquent与分组和排序有很多关系

时间:2018-06-04 19:04:12

标签: laravel eloquent

我正在使用Laravel 5.6,并希望获得过去两周内发布的精选文章集合,这些文章按上周的观看次数排序。理想情况下在模型上使用分页。

DB:

author (id, name, ....)
article (id, title, content, publish_date, ...)
article_view (id, article_id, date, views)
featured_article (id, article_id, created_at)

模型

class Author extends Model
{
    protected $table = 'author';
    public function articles()
    {
        return $this->hasMany(Article::class,'id','author_id');
    }
}

class Article extends Model
{
   protected $table = 'article';
   public function author()
   {
        return $this->hasOne(Author::class,'id','author_id');
   }
}

class FeaturedArticle extends Model
{ 
   protected $table = 'featured_article';
   static public function getFeaturedArticles($limit)
   {
     $articles = FeaturedArticles::where('created_at', '>=', Carbon::now()->subDays(14))->with(['article.author','article.articleViews'])->paginate($limit);
   }
}

然后在控制器或功能或作业中

$featured_articles = FeaturedArticle::getFeaturedArticles(15);

这样可以正常工作,但结果尚未排序。如何在7天内通过article_view.views的总和对分页结果进行排序。有可能吗?

1 个答案:

答案 0 :(得分:0)

假设您首先想要观看次数最多的文章:

class FeaturedArticle extends Model
{
    public function articleViews() {
        return $this->hasMany(ArticleView::class, 'article_id', 'article_id');
    }
}

$articles = FeaturedArticle::where('created_at', '>=', Carbon::today()->subDays(14))
    ->withCount(['articleViews' => function($query) {
        $query->select(DB::raw('sum(views)'))
            ->where('date', '>=', Carbon::today()->subDays(7));
    }])
    ->orderByDesc('article_views_count')
    ->with('article.author', 'article.articleViews')
    ->paginate($limit);

我将Carbon::now()替换为Carbon::today()。否则,您将无法获得在now()之前14天发布的文章。

此外,您的关系不正确:

public function articles()
{
    return $this->hasMany(Article::class, 'author_id', 'id');
}

public function author()
{
    return $this->belongsTo(Author::class, 'author_id', 'id');
}