【发布时间】:2019-09-26 04:42:11
【问题描述】:
制作像 miniinstagram 这样的应用程序,我们有推荐(帖子)和可以评论它们的用户。通过api获取数据。并且在获取所有 cmets 和某些帖子的所有回复时遇到问题。
我有一个数据库表
comment
-------------------------------
|id |
|text(comment text) |
|recommendation_id(post_id) |
|user_id(author) |
|parent_id(parent comment id) |
-------------------------------
在 parent_id 中我们可以设置父评论 id 。评论有回复,回复也有回复。 这里评论模型
class Comment extends Model
{
protected $with = ['user:id,name'];
protected $table = 'comments';
protected $fillable = ['text','user_id','recommendation_id'];
public function recommendation()
{
return $this->belongsTo('App\Models\MobileApp\Recommendation' , 'recommendation_id');
}
public function user()
{
return $this->belongsTo('App\User');
}
public function replies()
{
return $this->hasMany('App\Models\MobileApp\Comment' ,'parent_id');
}
public function parent()
{
return $this->belongsTo('App\Models\MobileApp\Comment' ,'id');
}
}
和 推荐模型
class Recommendation extends Model
{
protected $table = 'recommendations';
protected $fillable = ['course_id','title','description','file'];
public function comments()
{
return $this->hasMany('App\Models\MobileApp\Comment')->where('parent_id', '=', Null);
}
}
这里推荐控制器方法索引
public function index()
{
$recommendations = Recommendation::all();
foreach($recommendations as &$item){
//changing to full path
$item['file'] = 'https://example.com/' . $item['file'];
//getting comments
$item['comments']=$item->comments;
//getting replies
foreach($item->comments as $alphabet => $collection) {
$collection->replies;
//if reply array not empty then look for child repliese. I should have here recursive
if($item->comments[$alphabet]->replies->count()>0){
foreach($item->comments[$alphabet]->replies as $alphabet => $collection) {
$collection->replies;
}
}
}
}
if ($recommendations)
{
$response = ['success'=>true, 'data'=>$recommendations];
}
else
$response = ['success'=>false, 'data'=>'Record doesnt exists'];
return $response;
}
问题是如果我得到的回复不是空的,那么我必须寻找孩子的回复。我应该有类似 recursive 的东西。我该怎么做?
更新: 你好。我在帖子、cmets 和回复中添加了设置喜欢功能。并且有一些问题。我有“喜欢”表,它有 ['user_id','likeobject_id']。 Comment 和 User 之间是多对多的关系。我已添加到 Comment 模型中
public function CommentLikesCount()
{
return $this->belongsToMany('App\User','likes' ,'likeobject_id','user_id')->withPivot('likeobject')->where('likeobject', '=', 2);
}
这里 likeobject 只是意味着它是评论而不是帖子。没关系 。 并添加到 User 模型中
public function CommentLikes()
{
return $this->belongsToMany('App\Models\MobileApp\Comment','likes' ,'user_id','likeobject_id')->withPivot('likeobject')->where('likeobject', '=', 2);
}
然后添加到
foreach ($recommendation->comments as $comment) {
$comment->loadRecursiveReplies();
$comment['comment_likes']=$comment->CommentLikesCount->count();
}
但它只显示第一条评论的点赞数。供家长评论。不用于回复。
我添加了这个。但它不起作用。
public function loadReplies() {
return $this->load('replies.CommentLikesCount');
}
【问题讨论】: