Anyone can help me here?
Eloquent and pivot table problems
I'm having three problems related to Eloquent, and pivot table.
I have a simple role system using many to many relationship, and also I have projects. There will be administrators, developers and costumers on the website, but it happens that developers can create projecs, it means that the developer is administrator of his project, he can also add others to be administrator or to watch the project. The thing is that I want to reuse the roles system, knowing that the roles names are equal, at least for most of them, and for that I created a pivot table called project_user, with project_id, user_id and role_id.
The problems:
1º - In order to add a new user to a project I have to specify the ` role_id, something like that: `$project->users()->attach($user, ['role_id' => $role->id]), it works, but I can't attach more than one role to that user in a project. I read the documentation and it says that I can pass an array, but I got some errors:
$project->users()->attach([
$user, ['role_id' => 1],
$user, ['role_id' => 2]
]);
I hard-coded the id of the roles just as an example, and I got this:
Illuminate\Database\QueryException with message 'SQLSTATE[HY000]: General error : 25 bind or column index out of range (SQL: insert into "project_user" ("created_ at", "project_id", "updated_at", "user_id") [... really big]
As you an see in this small part of the error, there's no role_id.
2º - As I mentioned above, it works if I attach a user with one role, but the problem is that I can't retrieve that role as an object, only its id, isn't there a way to associate the ` role_id with the id of role's table, just like the pivot table does with the `project_i and `user_i? If not, what can I do, I really want to avoid doing another query just to retrieve the role.
3º - This one is related to `onDelet. As you can see on the code below, the `user_rol has an onDelete method that says that when the role is deleted, delete the record related to it on the pivot table. It works for `user_rol, but it doesn't work for the `project_use, even if the role has been deleted, the `project_use's record still there with the ` role_id.
I decided to link the code in other place to avoid too much code in the thread... and it won't get offline as it's on github.
You can see the code here: gist.github.com
Thank you very much.
Please or to participate in this conversation.