4spacesdk / CI4OrmExtension

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

Get multiples Roles of a User #10

Closed Gabriel-Arthur closed 3 years ago

Gabriel-Arthur commented 3 years ago

Following the documentation I have the database structure below

bd

how can i get all the roles of a user, because the code below


$UserModel = new UserModel();
$user = $UserModel
    ->includeRelated(RoleModel::class)
    ->find(1);

var_dump($user->toArray());

returns


array (size=4)
  'id' => int 1
  'name' => string 'user 1' (length=6)
  'email' => string 'email user 1' (length=12)
  'roles' => 
    array (size=1)
      0 => 
        array (size=2)
          'id' => int 1
          'name' => string 'god' (length=3)

I can even return correctly in an array like this


array (size=4)
  'id' => int 1
  'name' => string 'user 1' (length=6)
  'email' => string 'email user 1' (length=12)
  'roles' => 
    array (size=2)
      0 => 
        array (size=2)
          'id' => int 1
          'name' => string 'god' (length=3)
      1 => 
        array (size=2)
          'id' => int 3
          'name' => string 'user' (length=4)

doing something like that


$UserModel = new UserModel();
$user = $UserModel->find(1);
$roles = $user->roles->find();

$user = $user->toArray();
$user['roles'] = $roles->allToArray();

var_dump($user);

but, the instance of User don't have all the Roles and I can't set.

This is a problem?

Thanks a lot!

Martin-4Spaces commented 3 years ago

Hi Gabriel, I think what is most important here, is to understant that includeRelated is the same as doing a join. So in your first example, you get 2 users returned. One for each related role.

This code should explain.

        Data::debug(get_class($this), "Joining user table with roles table. Resulting in one row for each role");
        $userModel = new UserModel();
        $user = $userModel
            ->includeRelated(RoleModel::class)
            ->where('id', 1)
            ->find();
        Data::debug($user->allToArray());

        Data::debug(get_class($this), "Fetching roles user afterwards will put all roles on the user object");
        $userModel = new UserModel();
        $user = $userModel->find(1);
        $user->roles->find();
        Data::debug($user->toArray());

Resulting in localhost_8580_Home_roles

Here is the complete project I used to test this issue. CI4Playground.zip

Gabriel-Arthur commented 3 years ago

Omg, this is so simple!!

Thank you !!