Skip to content
Advertisement

Determine selected options based on many-to-many relationship

I have three tables: products, categories and category_product.

In my edit form page I’m displaying the categories and subcategories values in a select box. The chosen category options are saved in the pivot table category_product. This table has product_id and category_id.

Here’s my code.

Product model

JavaScript

Category model:

JavaScript

edit product page view:

JavaScript

subcats-select view

JavaScript

How can I put “selected” attribute to the chosen category options, so when I edit the page to apply the changes properly?

Advertisement

Answer

You can get pivot table columns the following way:

Product model

JavaScript

edit product page View:

JavaScript

EDIT: While the above answer might be helpful for others, it doesn’t answer the question. So here’s my second try after some clarification in the chat.

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement