4spacesdk / CI4OrmExtension

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

has many relation not good #16

Closed Noext closed 2 years ago

Noext commented 2 years ago

step 1 : follow the tutorial step 2 : use Setup as exemple step 3: call save_relationsin Crud step 4 : you get a array with the same user with one role each time instead of one user and a roles array { "id": 7, "name": "With all roles", "color_id": 1, "user_detail_id": 0, "roles": [ { "id": 2, "name": "employee" } ] }, { "id": 7, "name": "With all roles", "color_id": 1, "user_detail_id": 0, "roles": [ { "id": 1, "name": "admin" } ] }

( see picture as proof ) https://i.imgur.com/XmGjNQI.png

Martin-4Spaces commented 2 years ago

@Noext Please take a look at my answer here https://github.com/4spacesdk/CI4OrmExtension/issues/10 :)

Noext commented 2 years ago

what if i want all users with all their roles ?

Martin-4Spaces commented 2 years ago

You can either do it like this

$allUsers = (new UserModel())->find();
foreach($allUsers as user) {
    $user->roles->find();
}

Or

  1. Find all users
  2. Find all roles_users (includeRelated(RoleModel::class)
  3. Loop $rolesUsers and add role to each user $allUsers->getById($rolesUser->user_id)->roles->add($rolesUser->role)
Noext commented 2 years ago

too bad that a deal breaker for me, i'm running a API and i cant do that on multiple relation every time i need a object in my database

Martin-4Spaces commented 2 years ago

I've solved this issue in my API by using https://github.com/4spacesdk/CI4RESTExtension. Here I can fetch users by including roles like this /api/v1/users?include=role. The CI4RESTExtension will automatically find relations and add to users. Without me doing any code for it. I don't believe this should be handled by an Orm which is why I do it in the API.

Noext commented 2 years ago

i'm already using a other ci4 ext for the API REST , that why i cant use CI4RESTExtension.