本文介紹了Laravel hasMany 關系統計帖子的點贊數和評論數的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
代碼:
$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. I only display a few of the comments initially to avoid large loads. But I want to show how many the total comments and likes for each post. How do I do this?
型號代碼:
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 中獲取我想要的所有數據.但我也想加上總數.
Just by using that I get all the data i want in the json. But I also want to add the total counts.
更新
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)
推薦答案
在您的模型中放置以下訪問器:
In your model place the following accessors:
點贊總數:
public function getTotalLikesAttribute()
{
return $this->hasMany('Like')->whereUserId($this->author_id)->count();
}
統計評論總數:
從你的描述中,我可以看到,你已經檢索了作為評論的帖子數量
From your description, i can see, you have retrieving the number of posts as comments
public function getTotalCommentsAttribute()
{
return $this->hasMany('Post')->whereUserId($this->author_id)->count();
}
現在,從您的控制器:
$post = Jumpsite::find($jid);
// total comments
var_dump( $post->total_comments );
// total Likes
var_dump( $post->total_likes );
這篇關于Laravel hasMany 關系統計帖子的點贊數和評論數的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!