0
votes

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
2
Welcome to StackOverflow! When you use 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

2 Answers

0
votes

You should rename your getCategory() function to simply category(). That makes the relation names much more straightforward and probably fixes your issue.

THEN, you should be able to call whereHas('category', ...).

If it still does not work, simply chain a ->toSql() to any of your queries and debug the actual query that way.

0
votes

apparently everything is fine!

One suggestion is to add two more parameters to the belongsToMany method, like:

public function getCategory()
{
    return $this->belongsToMany(Category::class, 'post_category', 'post_id', 'category_id');
}

https://laravel.com/api/7.x/Illuminate/Database/Eloquent/Concerns/HasRelationships.html#method_belongsToMany