Reputation: 18273
I'm really confused at the moment, and I hope you can help me find the way :)
Let's say I have 2 models:
Every user can be part of one or more groups, and every group can have one or more users. Both of the models are built with ORM (I'm developing in Kohana 3.2, but the framework maybe is not so important here).
The problem comes when I want to add a user to a group, and I only have the user id, and the group id.
$user = ORM::factory('user', $user_id);
$group = ORM::factory('group', $group_id);
$group->add('user', $user);
So I should have 3 db request. But I want to resolve the problem with a single request.
I'm thinking about creating a helper class: group having a method *add_user* acception 2 parameters (group_id, user_id), and in this method I will make a single database request to insert a record in the *groups_users* table, to insert the user in the group.
What is a better way for this?
Upvotes: 0
Views: 97
Reputation: 3145
Im a Kohana user. What's wrong with just doing this:
$group = ORM::factory('group');
$group->user_id = $user_id;
$group->group_id = $group_id;
try
{
$group->save();
} catch(ORM_ValidationException e) {
//deal with error
}
I might have misspelled the validation exception but you get the idea.
Upvotes: 1
Reputation: 160843
3 db request is necessary, because you should make sure the user and group by the giving id does exist. The ORM way make the code more readable.
Upvotes: 2