Code:
$posts = Jumpsite::find($jid) ->posts() ->with('comments') ->with('likes') ->with('number_of_comments') ->with('number_of_likes') ->where('reply_to', 0) ->orderBy('pid', 'DESC') ->paginate(10);
Each post has a comment and likes. First, I show a few comments to avoid heavy loads. But I want to show how many total comments and comments for each post. How to do it?
Model Code:
public function likes() { return $this->hasMany('Like', 'pid', 'pid'); } public function comments() { return $this->hasMany('Post', 'reply_to', 'pid')->with('likes')->take(4); } public function number_of_likes() { return $this->hasMany('Like', 'pid', 'pid')->count(); }
Note:
This is an API. All will be returned as JSON.
Update
Return
Post author_id message Comments(recent 4) user_id message post_date Number_of_likes Likes user_id Number_of_total_comments Number_of_total_likes
Update
How do I return data
$posts = $posts->toArray(); $posts = $posts['data']; return Response::json(array( 'data' => $posts ));
Just using this, I get all the data I want in json. But I also want to add a general score.
Update
protected $appends = array('total_likes'); public function getTotalLikesAttribute() { return $this->hasMany('Like')->whereUserId($this->uid)->wherePostId($this->pid)->count(); }
but getting an error:
Unknown column 'likes.post_id'
Error
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'likes.post_id' in 'where clause' (SQL: select count(*) as aggregate from `likes` where `likes`.`deleted_at` is null and `likes`.`post_id` = 4 and `pid` = 4 and `uid` = 1)
source share