如何解决通过 2 个模型建立雄辩的关系
我有 Post 模型:
class Post extends Model
{
use HasFactory;
protected $fillable = [
'category_id','user_id','img','title','content',];
public function user(){
return $this->belongsTo(User::class);
}
public function category(){
return $this->belongsTo(Category::class);
}
public function comments(){
return $this->hasMany(Comment::class)->where('parent_id','0');
}
}
评论模型:
class Comment extends Model
{
use HasFactory;
protected $fillable = [
'post_id','parent_id',// 'img'
];
public function user()
{
return $this->belongsTo(User::class);
}
public function replies()
{
return $this->hasMany(Comment::class,'parent_id');
}
}
@foreach($comments->comments->replies->sortByDesc('id') as $comment)
@endforeach
<div class="col-md-12">
<div class="blog-comment">
<hr/>
<ul class="comments">
<li class="clearfix">
@foreach($post as $comments)
@foreach($comments->comments->sortByDesc('id') as $comment)
<img src="https://bootdey.com/img/Content/user_1.jpg" class="avatar">
<div class="post-comments">
<p class="Meta d-flex justify-content-between"><a href="#">{{ $comments->user->name }}</a><span>{{ $comments->user->created_at }}</span></p>
<p>
{{ $comment->content }}
</p>
</div>
<form action="{{ route('comment.store') }}" method="POST" class="w-100">
@csrf
<div class="replyform d-flex mb-3">
<input type="hidden" name="post_id" value="{{ $comments->id }}">
<input type="hidden" name="parent_id" value="{{ $comment->id }}">
<input class="d-block ml-auto w-50 align-top" type="text" name="content" required>
<button type="submit" class="offset replysub fas fa-paper-plane ml-1"></button>
</div>
</form>
@endforeach
@endforeach
@foreach($comments->comments->replies->sortByDesc('id') as $comment)
@if($comment->parent_id !== 0)
<ul class="comments">
<li class="clearfix">
<img src="https://bootdey.com/img/Content/user_3.jpg" class="avatar">
<div class="post-comments">
<p class="Meta">Dec 20,2014 <a href="#">JohnDoe</a> says : <i class="pull-right"><a href="#"><small>Reply</small></a></i></p>
<p>
{{ $comment->content }}
</p>
</div>
<input class="replyform d-block ml-auto mb-3 w-50" type="text" name="" value="">
</li>
</ul>
@endif
@endforeach
</li>
</ul>
</div>
</div>
当然,我可以将另一个变量传递给模板,但我听说你不应该这样做,它会使控制器过载。因此,我尝试通过雄辩的关系来做到这一点。
附言或者有没有办法在后期模型中做到这一点?喜欢:
public function replies(){
return $this->hasMany(Comment::class)->where('parent_id','id(of parent comment)');
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。