Home > database >  Laravel ORM: How to filter records from a table in a M:M relation using a condition of the other tab
Laravel ORM: How to filter records from a table in a M:M relation using a condition of the other tab

Time:10-22

I have those two tables: apps and categories, they are in a M:M relationship, I have the apps_categories table in place and the BelongsToMany() relations in their models, they work fine.

Now, in a form I'm displaying all the records in apps, but I want to filter based on category_id, so I have a $categories array where I store the filters.

My problem is solved using the DB facade doing like:

$apps = DB::table('apps')
  ->join('apps_categories', 'apps.id', '=', 'app_id')
  ->whereIn('category_id', $categories)
  ->select('apps.*')
  ->get();

So, I was wondering if there's a better way, using only the ORM. Thing is I have another table with a M:M relationship to apps, and I'm supposing using the ORM would be a better way to handle both relationships

CodePudding user response:

You could use the whereHas method for this:

$apps = App::whereHas('categories', function ($query) use($categories) {
    $query->whereIn('categories.id', $categories);
})->get();

Same as the above but uses an arrow function:

$apps = App::whereHas('categories', fn ($query) => $query->whereIn('categories.id', $categories))->get()

The 1st argument for whereHas is the method name you have used for the relationship in your model (categories) and 1st argument for the whereIn is the table name and field (categories.id).

  • Related