duanao2585 2015-02-25 22:25
浏览 1239
已采纳

将Laravel DB :: raw()查询与join连接到Eloquent

I have a Model 'Picture' (database table 'uploaded_pictures') that has many 'Like'(s)

private function likeWrapper() {
    return $this->hasMany( 'Like', 'typeId');
}

public function likes() {
    return $this->likeWrapper()->where( 'type', '=', Config::get( 'enums.content_types.PICTURE' ) )->get();
}

Now I want to create a page, paginated, that returns all Pictures ordered by the count of likes. I made this work using the Collection sortBy method:

$pictures = Picture::get()->sortByDesc( function($picture) {
        return $picture->likes()->count();
});

But this result can't be paginated. I have a raw query that does the job, but I struggle translate it to Eloquent query builder:

        $query = "SELECT p.*,  COUNT(l.id) AS countLikes
            FROM uploaded_pictures AS p
            LEFT OUTER JOIN
                (SELECT id, typeId, type FROM likes WHERE type='picture') AS l
            ON p.id = l.typeId
            WHERE  date<='$referenceDate'
            GROUP BY p.id, l.typeId
            ORDER BY countLikes DESC";

    $pictures = DB::select(DB::raw($query));

What is the equivalent of this query in Eloquent? I'm using Laravel 4.2.11.

  • 写回答

1条回答 默认 最新

  • drqwbh2150 2015-02-26 01:28
    关注

    I hope it will work :

            $pictures = Picture::leftjoin('likes', 'pictures.id', '=', 'likes.typeId')
                        ->select(DB::raw('pictures.*, COUNT(likes.id) as countLikes'))
                        ->where('likes.type', '=', 'Picture')
                        ->orWhere('likes.typeId')
                        ->orderBy('countLikes', 'DESC')
                        ->groupBy('pictures.id')
                        ->get();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里