Jun 7, 2022
11
Level 4
How to write this script?
I have general pivot table which represents data:
+----+------------+--------+
| id | product_id | tag_id |
+----+------------+--------+
| 1 | 56 | 1 |
+----+------------+--------+
| 2 | 56 | 5 |
+----+------------+--------+
| 3 | 56 | 3 |
+----+------------+--------+
| 4 | 89 | 1 |
+----+------------+--------+
| 5 | 89 | 9 |
+----+------------+--------+
| 6 | 89 | 2 |
+----+------------+--------+
| 7 | 89 | 5 |
+----+------------+--------+
Then I have multidimensional array which represents filter:
$selected = [
0 => [5, 6]
1 => [7, 8]
2 => [9]
];
I want retrieve all product_id from pivot table that fits array filter.
Get all product_ids WHICH HAVE tag_id (5 OR 6) AND (7 OR 8) AND (9).
Level 75
$productIds = Product::where(function ($query) use ($selected) {
foreach ($selected as $tagIds) {
$query->whereHas('tags', function ($query) use ($tagIds) {
foreach ($tagIds as $tagId) {
$query->orWhere('id', $tagId);
}
});
}
})->pluck('id');
Please or to participate in this conversation.