Love Fuel?
Donate
About
Forums
Discussions
Login
FuelPHP Forums
Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
General
Relations: Many To Many
apkahym
May 2017
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?
Harro
May 2017
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.
apkahym
May 2017
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
Harro
May 2017
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.
;-)
apkahym
May 2017
Thanks anyway.
With your contribution I finished the module.
Thank you very much.
Add a Comment
Howdy, Stranger!
It looks like you're new here. If you want to get involved, click one of these buttons!
Sign In
Apply for Membership
Categories
All Discussions
5,088
General
↳ General
3,364
↳ Job Board
13
↳ Installation & Setup
214
Packages
↳ Oil
213
↳ Orm
700
↳ Auth
260
Development
↳ Tips and Tutorials
126
↳ Code share
145
↳ Applications
52
In this Discussion
apkahym
May 2017
Harro
May 2017