1
votes

I'm using cakephp 3.0, and I have a 'users' table, and a 'profiles' table. The users-table contains minimum information, username, e-mail, password. The profiles-talbe contains detailed information : avatar, phone number, ...

I am able to link those 2 tables together with a hasMany association. And if I look at the output of a user, it shows the 'profiles' property, as an array, with an item for each profile information:

User (array)
   id    1
   username    admin
   email       [email protected]
   password    ****
   -> created  (array)
   -> modified (array)
   -> profiles (array)
         -> 0  (array)
              id         1
              user_id    1
              key        avatar
              value      1.jpg
         -> 1  (array)
              id         2
              user_id    1
              key        phone
              value      555-1234

No it's still hard to get the Avatar. I'll have to go through all the profile-items to see which has the key 'avatar'. What I'm looking for is something which will give this structure:

User (array)
   id    1
   username    admin
   email       [email protected]
   password    ****
   -> created  (array)
   -> modified (array)
   -> profiles (array)
         avatar       1.jpg
         phone        555-1234

This would be much easier. Now I can just to User->profiles->avatar.

Is that possible?

1
Do you really need a hasMany relationship? Surely a hasOne relationship is more appropriate?drmonkeyninja
How it that? A user can have multple profile items. Like an avatar or a phone or ... I don't want to create a table with a column 'avatar' and a column 'phone, ...Spippo
Sorry, misread your data structure.drmonkeyninja
It's a lot more standard to have a "profiles" table with a hasOne association that has all the fields 'avatar', 'phone', nickname ...etc. As opposed to having a single row for every possible option. Just seems overkill doing it the way you're doing it, and it's making your resulting dataset more confusing too.Dave
Is it? Because it is less flexible. Let's say I have my whole site up-and-running and in production. And I feel the need to add a nickname to the profile. Not only do I need to update the table structure, but also the Entity and Table files.Spippo

1 Answers

1
votes

You could do this using the Hash utility to manipulate your returned array:-

$data['profiles'] = Cake\Utility\Hash::combine(
    $data['profiles'], 
    '{n}.key', 
    '{n}.value'
);