【发布时间】:2017-09-29 21:12:46
【问题描述】:
代码:
$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);
每个帖子都有评论和喜欢。我最初只显示几个 cmets 以避免大负载。但我想显示每个帖子的总 cmets 和喜欢的数量。我该怎么做?
型号代码:
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();
}
注意:
This is an API. All will be returned as JSON.
更新
回报
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
更新
我如何返回数据
$posts = $posts->toArray();
$posts = $posts['data'];
return Response::json(array(
'data' => $posts
));
只需使用它,我就可以在 json 中获得我想要的所有数据。但我也想添加总数。
更新
protected $appends = array('total_likes');
public function getTotalLikesAttribute()
{
return $this->hasMany('Like')->whereUserId($this->uid)->wherePostId($this->pid)->count();
}
但得到错误:
Unknown column 'likes.post_id'
错误
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)
【问题讨论】:
-
您想统计每个帖子还是需要特定帖子时?
-
@Anam 我想统计每个帖子的数量。这就像一个饲料。让我们说一个 Facebook 时间线。
-
Post 中的 author_id 和 likes 中的 user_id 有什么不同?他们是一样的吗?
-
你的
likes表中有post_id列吗? Laravel 在 likes 表中找不到 post_id。 -
@Anam 不,我不知道。我在所有表上都有 user_id 的 uid 和 post_id 的 pid。我如何告诉 laravel 找到 pid?
标签: php mysql laravel eloquent