简体   繁体   中英

Translate Laravel DB::raw() query with join to 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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM