Amir
Amir

Reputation: 29

laravel querying many to many

I have 2 models, Service and Category. They are related with a many-to-many relationship like so:

Service.php

public function categories()
{
   return $this->belongsToMany('App\Category')->withTimestamps();
}
Category.php

public function services()
{
   return $this->belongsToMany('App\Service')->withTimestamps();
}

And of course they're joined by a pivot table:

category_service

  - category_id
  - service_id
  - created_at
  - updated_at

I'd like to use local scope to filter service result based on IDs of categories. I've done the following:

Service.php

public function scopeFilter($query, $category_ids)
{
    $services = Service::whereHas('categories', function (Builder $query) use ($category_ids) {
        $query->whereIn('category_id', $category_ids)->get();
    });

    return $services;
}

But I'm getting a Column not found error, specifically:

Column not found: 1054 Unknown column 'services.id' in 'where clause' (SQL: select * from `categories` inner join `category_service` on `categories`.`id` = `category_service`.`category_id` where `services`.`id` = `category_service`.`service_id` and `category_id` in (1, 2))

1 and 2 are the category IDs I pass.

I wrote the function based on the answer I found here and here.

Any pointers?

Upvotes: 1

Views: 46

Answers (1)

TsaiKoga
TsaiKoga

Reputation: 13394

Your error message show that your query is begin with categories and without join services.

So put the ->get() outside the closure.

public function scopeFilter($query, $category_ids)
{
    $services = Service::whereHas('categories', function (Builder $query) use ($category_ids) {
        $query->whereIn('category_id', $category_ids);
    })->get();

    return $services;
}

Upvotes: 1

Related Questions