D
D
Daniil Kondratovich2015-09-15 13:09:09
MySQL
Daniil Kondratovich, 2015-09-15 13:09:09

Many-to-many relationship with join in Laravel?

There are 3 tables: products, product_parameter, parameters.
In products, there are 2 products that have certain parameters that are listed in the parameters table. The product_parameter table is the link table.
The task is to filter products by parameters. No matter how hard I tried, extra copies of products were always displayed. I decided once again to start from scratch, I wrote the following code.

$goods = DB::table('products')
      ->join('product_parameter as product_parameter', 'products.id', '=', 'product_parameter.product_id')
      ->join('parameters as parameters', 'product_parameter.parameter_id', '=', 'parameters.id')
      ->select('products.*')->get();

The result is the following: issued 6 objects, that is, three copies for each product! And then I realized that, most likely, the whole point is in the linking table, or rather, in the wrong links, because it contains exactly six linking records.
Actually the question is: what needs to be fixed so that records are displayed without copies, both with a normal query and when filtering by parameters?
Ps: Left join didn't change the situation.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vyacheslav Plisko, 2015-09-15
@ktulxu

Use ORM, not DB::table, no need to suffer. And so the result is correct, for each match you have an extra record and then you need to group by a unique field. Maybe it will work - groupBy('products.id')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question