Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
Relations: Many To Many
  • Hi everyone,

    Now I need help with the many_to_many.

    I pass an php array with id's of roles when i am creating the user.
    But i can't make the relation role_id with user_id in this moment.

    I have this code on my controller:

    $ User = new \ Model \ Auth_User;

                $ User-> username = Input :: post ('username');
                $ User-> password = Auth :: instance () -> hash_password ('password');
                $ User-> email = Input :: post ('email');
                $ User-> group_id = Input :: post ('group_id');
                $ User-> last_login = '0';
                $ User-> previous_login = '0';
                $ User-> login_hash = '';
                $ User_roles = Input :: post ('user_roles');

                $ User-> roles [] = \ Model \ Auth_Role :: forge ();
    // $ user-> roles = $ user_roles;
    // Auth :: create_user ($ user, $ password, $ email, $ group_id, array ());

                If (isset ($ user_roles)) {
                    Foreach ($ user_roles as $ user_role) {
                        $ User-> roles [] = $ user_role;
    // $ user-> roles-> role_id = $ user_role;


                $ User-> save ();

    And get this error

    Invalid Model instance added to relations in this model.

    Can help me?
  • HarroHarro
    Accepted Answer
    One to many and many to many relations work exactly the same from the point of the parent, both are represented by an array of child objects.

    So assuming $_POST['user_roles'] is an array of Auth\Model_Role id's, you can simply do

    $user->roles = \Auth\Model::role->query()->where('id', 'IN', \Input::post('user_roles', array()))->get();

    The ORM will automatically delete the junction records of the related roles that are no longer assigned.
  • Great, I had a little change, and I have to use

    $ User-> roles = \ Model \ Auth_Role :: query () -> where ('id', 'IN', \ Input :: post ('user_roles', array ())) -> get ();

    Because I get an error with a "->" character.
    But now it works.

    Now I need to get the roles associated with the user to display on edit view.

    Help me :D
  • HarroHarro
    Accepted Answer
    Sorry, my mistake, made a typo in the example.

    And also sorry, but I'm not going to write your application for you. If you want that, we have a paid service you can use. ;-)
  • Thanks anyway.
    With your contribution I finished the module.
    Thank you very much.

Howdy, Stranger!

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

In this Discussion