4spacesdk / CI4OrmExtension

OrmExtension for CodeIgniter 4
MIT License
50 stars 9 forks source link

Is there a way to save relationship? #19

Closed etcware closed 2 years ago

etcware commented 2 years ago

I know that this is not the correct way to communicate, but I need another suggestion. May be useful to insert these suggestions in documentation... I have an UserModel with the classical relationship many to many

public $hasMany = [
        GroupModel::class
    ];

And the symmetrical GroupModel with

public $hasMany = [
        UserModel::class
    ];

When I save a user may I save also a group relation? That is a row in users_groups?

$user->firstname = $this->request->getPost('firstname');
        $user->lastname = $this->request->getPost('lastname');
        $user->name = $this->request->getPost('name');
        $user->email = $this->request->getPost('email');
        $user->password = $this->request->getPost('password');
        $user->password_hash = $this->request->getPost('password');
        $user->password_confirm = $this->request->getPost('password_confirm');
        $user->activate_hash = random_string('alnum', 32);
//         dd($this->request->getPost('group'));
        $group_id = $this->request->getPost('group');
        if (is_numeric($group_id)) {
            $user->groups = $groupModel->find($group_id);
            if (! $userModel->save($user)) {
                return redirect()->back()->withInput()->with('errors', $userModel->errors());
            }
        }
etcware commented 2 years ago

The many to many table name is groups_users.

Martin-4Spaces commented 2 years ago

You can easily save relations like this $user->save($group).

$user->firstname = $this->request->getPost('firstname');
$user->lastname = $this->request->getPost('lastname');
$user->name = $this->request->getPost('name');
$user->email = $this->request->getPost('email');
$user->password = $this->request->getPost('password');
$user->password_hash = $this->request->getPost('password');
$user->password_confirm = $this->request->getPost('password_confirm');
$user->activate_hash = random_string('alnum', 32);
$group_id = $this->request->getPost('group');
if (is_numeric($group_id)) {
    $user->groups = $groupModel->find($group_id);
    if (! $userModel->save($user)) {
       return redirect()->back()->withInput()->with('errors', $userModel->errors());
    }
    **$user->save($user->groups);**
}

It will automatically guess the table name groups_users and add a row without any GroupsUserModel and GroupsUser(Entity) classes required.

etcware commented 2 years ago

great!