【发布时间】:2021-10-26 16:35:50
【问题描述】:
我目前正在尝试在 3 个表之间建立关系。
post
id
name
category
id
name
post_category
id
post_id
category_id
数据库
邮政 | 1 |帖子1 | | 2 |帖子2 | | 3 |后3 | 类别 | 1 |猫1 | | 2 |猫2 | | 3 |三类 | post_category | 1 | 1 | 1 | | 2 | 2 | 1 | | 3 | 3 | 2 | | 3 | 2 | 2 | | 3 | 1 | 3 | 模型 Post.php 公共函数 getCategory() { 返回 $this->belongsToMany(Category::class, 'post_category'); } PostController.php $data = Post::with('getCategory')->get(); 它返回正确的帖子列表。现在我想按类别过滤帖子。我尝试,但它不起作用 $categoryId = [1,2]; $data = Post::with('getCategory')->whereHas('category', function ($query) use ($categoryId) { $query->whereIn('id', $categoryId); })->orderBy('id','DESC')->get(); 请帮我 使用 Laravel 5.4
【问题讨论】:
-
欢迎来到 StackOverflow!当你在关系区使用
whereHas或任何其他方法时,第一个参数是指你的模型的方法(getCategory),而不是表。看看@Flame 的回答。这就是建议。
标签: php laravel eloquent relationship