0

I have two tables variants and variant_attributes which have one to many relation.

Each variant has one or more rows in variant_attributes table.

A group of variants could have these

[
  1 => [13, 1, 18],
  2 => [13, 2, 18],
  3 => [13, 3, 18],
  4 => [14, 1, 18],
  5 => [14, 2, 18],
  6 => [14, 3, 18],
  7 => [15, 1, 18],
  8 => [15, 2, 18],
  9 => [15, 3, 18]
]

$attribute_id = [1, 13];

$variants->whereHas('variant_arrtibutes', function ($q) use ($attribute_id) {
    $q->whereIn('attribute_value_id', $attribute_id);
});

It returns variants with IDs [1, 2, 3, 4, 7] instead of only id = 1 as I want.

What went wrong?

linktoahref
  • 7,812
  • 3
  • 29
  • 51

1 Answers1

0

This happens because you are checking a variant has at least one of the attributes you provide. Try:

$variants->whereDoesntHave('variant_arrtibutes', function ($q) use ($attribute_id) {
    $q->whereNotIn('attribute_value_id', $attribute_id);
});
kris gjika
  • 531
  • 2
  • 8