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 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条