在laravel中调用数组错误的成员函数paginate()

时间:2017-12-05 13:15:43

标签: laravel-5 laravel-query-builder

我想在laravel中创建分页,但它会给出错误。 这里是错误"调用数组"

上的成员函数paginate()

这是我的查询

$blog = DB::select("select blog_post.*,(select img_name from blog_image WHERE blog_image.bid=blog_post.bid limit 0,1) as img_name, 
(SELECT count(*) FROM likes WHERE likes.bid =blog_post.bid) AS likes,
(SELECT count(*) FROM comment WHERE comment.bid =blog_post.bid ) as comments ,
(SELECT count(*) FROM blog_share WHERE blog_share.bid =blog_post.bid ) as  share 
from blog_post WHERE status=1 AND is_draft=0 AND is_publish=1 AND is_delete=0")->paginate(2);

1 个答案:

答案 0 :(得分:1)

首先需要使用Laravel Eloquent重写您的查询。例如:

$blog = DB::table('blog_post')->where([ 'status' => 1, 'is_draft' => 0, 'is_publish' => 1, 'is_delete' = 0 ])->paginate(2);

您并不需要将所有计数/内部查询放入一个查询中。您可以使用Eloquent Relationships和Mutators为您获取该信息。例如,以下关系来获取图像:

class BlogPost extends Model
{

  public function image()
  {
    return $this->hasOne('BlogImage');
  }

}