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

将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.

图片转代码服务由CSDN问答提供 功能建议

我有一个模型'图片'(数据库表'uploaded_pictures')有许多'喜欢'(s)< / p>

 私有函数likeWrapper(){
返回$ this-&gt; hasMany('Like','typeId'); 
} 
 
公共函数likes(){  
返回$ this-&gt; likeWrapper() - &gt; where('type','=',Config :: get('enums.content_types.PICTURE')) - &gt; get(); 
} 
    
 
 

现在我想创建一个页面,分页,返回按喜欢计数排序的所有图片。 我使用Collection sortBy方法完成了这项工作:

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

但是此结果无法分页。 我有一个原始查询来完成这项工作,但我很难将其转换为Eloquent查询构建器:

  $ 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&lt; ='$  referenceDate'
 GROUP BY p.id,l.typeId 
 ORDER BY countLikes DESC“; 
 
 $ pictures = DB :: select(DB :: raw($ query)); 
  <  / pre> 
 
 

Eloquent中此查询的等效内容是什么? 我正在使用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();
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题