我正在处理一个带有路由模型绑定的Laravel8项目。这是关于邮政的。Post与模型Comment之间存在一对多(多态(关系。注释有一个已批准的字段。这是一个布尔值。
如何显示已批准的帖子及其评论===true。我知道如果有条件的话,我可以抓住它。但我的目标是过滤已经在控制器中的评论。
public function show(Post $post)
{
dd( $post->comments );
return view('post', ['post' => $post]);
}
注释迁移,-模型:
Schema::create('comments', function (Blueprint $table) {
$table->id();
$table->text('comment_content');
...
$table->boolean('approved')->default(false);
$table->integer('commentable_id');
$table->string('commentable_type');
$table->timestamps();
});
// Comment Model
public function commentable()
{
return $this->morphTo();
}
后期模型
public function comments()
{
return $this->morphMany(PostComment::class, 'commentable');
}
仅应为批准的注释。
即使是变形关系,也可以使用加载方法加载:
$post->load(['comments' => function ($query) {
$query->where('approved', true);
}]);
我相信你只能加载对关系的批准评论,比如:
public function comments()
{
return $this->morphMany(PostComment::class, 'commentable')
->where('approved', 1);
}
MorphMany
来自Laravel的HasRelationships
类,您应该能够标记where
条件以根据需要对其进行筛选。