How to write many2many related data into db?

So far using AR has been fairly smooth sailing for me especially with the help of CRUD tools. However, I’ve hit a dead end.

I have a many to many relationship with a linker table:

tbl_exercise, tbl_exercise_link_template and tbl_template

The idea is that each template consists of may exercises. My template table only has two fields, id and name. The template is meant to then have a list of exercises as part of it, which is expressed in the linker table.

How do I create a form where I can create a new template with selected exercises (identified by their id)?

In the case of one form representing a table directly it is easy. You create a model instance for that table, read the form, validate -> save(). In the M:M case I need to use more than one model, right?

I’ve had a look around and I must be using the wrong search terms.

I’d appreciate any help.



finally found this:

I take it I have to use an extension?

I seem to have found three extensions covering the same functionality. This one has the most upvotes:

Any comments on what the current situation is would be more than welcome.

third edit: I’m just really confused. The example on the yii homepage only seems to do relational queries for retrieving data and doesn’t mention saving.

Somebody heeeeeeelp :expressionless:

You don’t need to use an extension.

Lets say you choose your M:M via multiselect, checkbox or dropdownlist in your form.

Then in your $_POST array you have some related data.

You basically need to loop through it and assign the data to a new model. I’ll give you a sample idea.



{//do some stuff, validate and save model, whatever



      foreach($_POST['relatedmodel'] as $key=>$value)

      $a=New RelatedModel;





Thanks for your reply.

I’m going slightly crazy so bear with me. From what I can understand you are showing me a way to feed two different models/tables through a single form, correct? If I understand you correctly, then your code has nothing to do with the linker table that resolves the m:m.

I have found yet another extensions which seems to be the latest one with all the previous versions merged and fixed. Here

I do have something working which allows me to create new instances of my template using the linker table to reference which exercises it should be linked with. I will have to sleep on this or at least take a break. I’ve googled myself into a yii-ActiveRecord-m:m craze.

edit: I’m still confused but I found this article on Ullman’s website. Is that what you were referring to?