I am currently trying to make a relation between 3 tables.
post
id
name
category
id
name
post_category
id
post_id
category_id
Database
post | 1 | post1 | | 2 | post2 | | 3 | post3 | category | 1 | cat1 | | 2 | cat2 | | 3 | cat3 | post_category | 1 | 1 | 1 | | 2 | 2 | 1 | | 3 | 3 | 2 | | 3 | 2 | 2 | | 3 | 1 | 3 |Model Post.php
public function getCategory() { return $this->belongsToMany(Category::class, 'post_category'); }PostController.php
$data = Post::with('getCategory')->get();It returns correct post list.
Now i want to filter the post by category. I try, but it not working
$categoryId = [1,2]; $data = Post::with('getCategory')->whereHas('category', function ($query) use ($categoryId) { $query->whereIn('id', $categoryId); })->orderBy('id','DESC')->get();please help me use Laravel 5.4
whereHas
or any other method in the relationship area, the first parameter refers to the method of your model (getCategory
), not the table. Look at @Flame answer. That's the recommendation. – Wahyu Kristianto