Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
Updating a many_many model on a related model
  • Hi. I'm having a little trouble getting a deep relationship to update when I save.

    Model_User has one Model_Profile, and Model_Profile is many to many with Model_Department.

    I've got cascade_save on for the user's relationship to profile, and for the profile's relationship to departments. My edit user form has a multiselect for the departments but when I try to save I get a message saying "Invalid Model instance added to relations in this model." 

    In the edit action of Controller_Users I'm relating it by having...

    $user->username = Input::post('username');
    $user->profile->firstname = Input::post('firstname');
    $user->profile->lastname = Input::post('lastname');
    $user->profile->departments = Input::post('departments');
    $user->save();


  • Assuming "->departments" is the relation, you can not assign strings to it, you have to assign related model objects to it. For a has_one/belongs_to relation, that is a single object, for the others, it's an array of objects.

    Again assuming this form returns a list of keys of selected departments, you'll have to fetch the existing departments, unset the ones not selected in the form, fetch the objects not already present in the relation, and add them, before saving.
  • OK, so much the same as saving would be without the ORM. Thanks.  
  • Works perfectly, thanks. For the record, for anyone googling, here's what I did...

                // we need to associate actual model objects, not just a list of IDs
                $departments = array();
                foreach(Input::post('departments') as $depid){
                    $departments[] = Model_Department::find($depid);
                }
                // unlink all the current user departments
                foreach ($user->profile->departments as $dep)
                {
                    if(!in_array($dep->id, Input::post('departments'))){
                        unset($user->profile->departments[$dep->id]);
                    }
                }
                $user->profile->departments = $departments;

                if ($user->save())
                ...
  • god bless you i search and try for 10hours to find out why this happening.
    thank you you are the first how tells someone what to do and not only write: "i solved it by my own..." and let the googlers in the dark xD (=hate this posts). love you for your comment dude! you saved my sleep :D
  • i updated your code little bit because it throws errors when i the parent model tries to add relation between an empty child model here you can find also the issue #283 on github

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion