Laravel join and distinct

Viewed 19477

In Laravel, I have a query which is:

$productsModel->join('tags', 'tags.item_id', '=', 'products.id')
      ->select('products.*', 'tags.item_id')
      ->distinct();

DB tables looks like this:
| products | tags    |
 ----------|---------|
| id       | id      |
|          | item_id |

products has a one to many relationship with tags, which creates issues when joining tables. As an example, I need to query products based on multiple tags, but I need to show only one product.

2 Answers
$tableA->select('table_a.id')
->join('table_b', 'table_a.id', '=', 'table_b.item_id')
->whereIn('table_b.id', [1, 2, 3])
->groupBy('table_a.id')
->get();

Select only that column which you want to group by.

Related