Search code examples
coldfusioncoldfusion-9cfwheels

cfWheels - creating an object related objects


I have a new model myModel that I'm creating with a one-to-many relationship to a bunch of sub-models mySubModel that are being created at the same time.

when I try to save the model:

<cfset myModel=model("myModel").new(params.mymodel)>
<cfset myModel.save()>

only the model part gets saved, the items inside params.myModel.mySubModels do not get created. The models have their relations setup and I can get it to pull the data in the same format out of myModel with the right include.

I could save each of the models separately, but I'm worried about that causing problems or just creating needles lines of code if cfwheels is able to handle this already. I would have to save the initial model and then save the additional sub-models, and if there is an error, delete the model and other sub-models that have already been written to the database.


Solution

  • As long as the main object relates to sub-objects with hasMany, Nested Properties will be invaluable to you.

    In the main model:

    function init() {
        hasMany("subModels");
        nestedProperties("subModels");
    }
    

    Then a call to save() in the controller runs saves on the parent object and all of its associated children.

    function create() {
        myModel = model("myModel").new(params.myModel);
    
        // This call to `save()` saves associated children represented in `params.myModel` too
        if (myModel.save()) {
            redirectTo(route="myRoute", success="The model was saved successfully.");
        }
        else {
            flashInsert(error="There was an error saving the model.");
            renderPage(action="new");
        }
    }
    

    If you can comment more about your particular data structure, I can help you with the form part. Calling something "subModel" is only going to get us so far in this discussion.