laravel表结构显示最喜欢的文章和更少的视图 [英] laravel table structure showing the most liked articles and less views

查看:84
本文介绍了laravel表结构显示最喜欢的文章和更少的视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用户可以添加文章,其他用户可以通过较少的查看来喜欢或不喜欢我最喜欢的

users can add articles and other users can like or dislike I need most liked with the less view

示例: 文章(A)具有500次观看和10个赞-文章(B)具有50次观看和10个赞 顺序将是(B)而不是(A)

example : article (A) has 500 views and 10 like - article (B) has 50 views and 10 likes the order will be (B) than (A)

这是我的数据库结构,我将它们连接在一起:

This is my database structure and I join them together:

文章表:

id | user_id | title | description | views | created_at | updated_at

顶表:

id | user_id | article_id | like_type | created_at | updated_at

查询以获取喜欢计数:

Article::leftJoin('likes', 'likes.article_id', '=', 'articles.id')
        ->select('articles.*', DB::Raw('SUM( 2 * likes.like_type -1) as likes_count'))
        ->groupBy('articles.
        ->get();

我该如何订购?

推荐答案

您可以通过链接orderBy在laravel中按多列进行排序.

You can order by multiple columns in laravel by chaining orderBy.

例如,在您的情况下,您将希望先按"likes_count"降序(=最大"),然后再按视图升序(=最小",这是默认值)进行排序.

In your case for example you will want to first order by "likes_count" descending (=biggest first) and then by views ascending (= smallest first, this is the default value).

所以您会这样做:

return Article::select('title', DB::Raw('SUM(2*likes.like_type-1) as likes_count'))
    ->leftJoin('likes', 'likes.article_id', '=', 'articles.id')
    ->groupBy('articles.id')
    ->orderBy('likes_count', 'DESC')->orderBy('views')
    ->get(); 

这篇关于laravel表结构显示最喜欢的文章和更少的视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆