首页 > 解决方案 > 在索引视图刀片中隐藏克隆帖子

问题描述

我的 livewire 显示刀片中有一个克隆功能,所以当用户克隆帖子时,我不希望克隆帖子显示在一般帖子视图刀片中

Post::get();

查看刀片

@foreach($posts as $post)
    {{ $post->title }}
@endforeach
``
 (

我不希望在索引中有相同的帖子

我只想在个人资料中显示用户克隆帖子

我该怎么做这个 livewire 组件

public function clone($id)
{
    $post = Post::find($id);
    $newPost = $post->replicate();
    $newPost->created_at = Carbon::now();
    $newPost->save();
}

标签: laravellaravel-8laravel-livewire

解决方案


您需要一种方法来确定帖子是否被克隆。为此,您可以cloned_post_idposts表中添加一个字段,然后在克隆它时,从原始帖子中设置 ID。

一旦你有了这些数据,你就可以过滤掉你寄存器中的克隆帖子——实现这一点的最好方法是在 Post 模型上添加一个关系,并检查它是否不存在——但你也可以检查whereNull('cloned_post_id').

克隆帖子,

public function clone($id)
{
    $post = Post::find($id);
    $newPost = $post->replicate();
    $newPost->cloned_post_id = $post->id;
    $newPost->updated_at = Carbon::now();
    $newPost->created_at = Carbon::now();
    $newPost->save();
}

然后在您的 Post 模型中,添加该关系,

public function clonedPost() 
{
    $this->belongsTo(Post::class, 'cloned_post_id');
}

然后在您的注册中,检查whereDoesntHave(),以排除被克隆的帖子,

$posts = Post::whereDoesntHave('clonedPost')->get();

推荐阅读