热门显示 laravel livewire 中具有相同类别 ID 的帖子?

Hot to show the posts that have same category id in laravel livewire?

livewire 组件路由绑定为:

Route::get('/post/{post}', Bycategory::class)->name('posts.by-category');

主视图我想点击类别名称并获取所有 post 具有相同类别的:

 @foreach($post->categories as $category)
   <a href="{{ route('posts.by-category', $category) }}">{{ $category->name }}</a>
 @endforeach

这是按类别 livewire class:

public Post $post;

    public function render()
    {

Post::with('categories')->where(function ($q){
    $q->where('category_id', $this->post->categories()->id);
})->get());
        return view('livewire.post.bycategory', compact('posts'))->layout('layouts.app');
    }

post 和类别与 category_post table

有多对多的关系

但我得到一个错误,在 Post 模型中没有 category_id;

$this->post->categories()->id 显示那个 post;

的类别 ID

正如您提到的上述错误,很明显 posts table 没有 category_id column,这就是您收到此错误的原因。我认为这是执行此查询的正确方法

Post::with('categories' , function ($query) { $query->where('categories.id', $this->post->categories()->id);} )->get());