我正在使用路由模型系結進行 Laravel8 專案。它是關于帖子的。Post與模型 Comment具有一對多(多型)關系。評論有一個已批準的欄位。這是一個布林值。
如何顯示帖子及其批準的評論 === true。我知道我可以用 if 條件在刀片中抓住它。但我的目標是過濾控制器中已有的評論。
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');
}
預計只有批準的意見。
uj5u.com熱心網友回復:
即使它是變形關系,您也可以使用load方法加載它:
$post->load(['comments' => function ($query) {
$query->where('approved', true);
}]);
uj5u.com熱心網友回復:
我相信您只能加載對關系的批準評論,如下所示:
public function comments()
{
return $this->morphMany(PostComment::class, 'commentable')
->where('approved', 1);
}
MorphMany來自 Laravel 的HasRelationships課程,您應該能夠標記where條件以根據需要對其進行過濾。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/364638.html
標籤:拉拉维尔
上一篇:Laravel翻譯
