Convert SQL to Eloquent to Join multiple table and

2019-08-27 17:44发布

I have been this SQL working fine, but trying to convert it to Eloquent format, it keeps returning a wrong, SQL entirely which flags error. Coding with Laravel 5.5

Select arm_articles.article_topic, arm_articles.id, arm_articles.article_id, 
COUNT(arm_article_views.view_article_id) AS TotalViews, 
COUNT( arm_article_likes.liked_article_id) AS TotalLikes, 
COUNT( arm_article_comments.comment_article_id) AS TotalComments
FROM arm_articles 
LEFT JOIN  arm_article_views  ON  arm_articles.article_id = arm_article_views.view_article_id 
LEFT JOIN  arm_article_likes  ON  arm_articles.article_id = arm_article_likes.liked_article_id 
LEFT JOIN  arm_article_comments  ON  arm_articles.article_id = arm_article_comments.comment_article_id 
GROUP BY arm_articles.article_id 
ORDER BY TotalLikes, TotalLikes, TotalComments ASC`

HOW I MADE ELOQUENT QUERY BUILDER Not working though:

return Datatables::of(PostModel::leftJoin('arm_article_views', 'arm_article_views.view_article_id', '=', 'arm_articles.article_id')
       ->leftJoin('arm_article_likes','arm_article_likes.liked_article_id', '=', 'arm_articles.article_id')
       ->leftJoin('arm_article_comments', 'arm_article_comments.comment_article_id','=','arm_articles.article_id')
       ->selectRaw(
           'arm_articles.*, 
           count(arm_article_views.view_article_id) AS ViewCount'
        ) 
        ->groupBy('arm_articles.article_id')->orderBy('ViewCount','DESC')
        ->where('arm_articles.article_contributor_id','=',$contributor_id)
        ->getQuery())->make(true);

Any hint would be appreciated

1条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-08-27 18:45

Try with this:

DB::table('arm_articles')
        ->leftJoin('arm_article_views', 'arm_articles.article_id', '=', 'arm_article_views.view_article_id')
        ->leftJoin('arm_article_likes', 'arm_articles.article_id', '=', 'arm_article_likes.liked_article_id')
        ->leftJoin('arm_article_comments', 'arm_articles.article_id', '=', 'arm_article_comments.comment_article_id')
        ->groupBy('arm_articles.article_id', 'article_topic')
        ->select(
            DB::raw('count(arm_article_views.view_article_id) as TotalViews'),
            DB::raw('count(arm_article_likes.liked_article_id) as TotalLikes'),
            DB::raw('count(arm_article_comments.comment_article_id) as TotalComments'),
            'arm_articles.article_id',
            'article_topic'
        )->get();
查看更多
登录 后发表回答