I'm developing a website where users will be able to save in their profile a list (array) of items (which they can find also in the same website and have their own id).
This is the way I've used so far in similar situations: - Create a 'text' (string) field in the users table in the DB and save the items separated by commas - To read that field, use the explode method to get the array in CakePHP and then work with it - To save the array to the DB, use the implode method to convert it to a string and be able to store it in the field
What I dont' like about this method is that it can get really complicated to deal with those lists (add items, remove items...) and you can't really access those items directly, there's always some pre-processing or post-processing to make.
For example, to make it easier to look at a specifc item in one user's list and find other users with the same item in their lists.
Is there any开发者_JAVA百科 better way to deal with arrays in CakePHP+MySQL? I've read about serialize()/unserialize(), but I don't think that would make a big difference compared to the other method...
Thank you very much in advance for any ideas!
Definately use a table so as with Kristian Antonsen's suggestion, create an items table then create a hasManu relationship in you User model like this:
class User extends AppModel{
$hasMany = array(
'Item'
);
}
Or A HABTM relationship:
class User extends AppModel{
$hasAndBelongsToMany = array(
'Item'
);
}
Use the form helper to create inputs for items.
Hope this helps.
A database table is just a huge spreadsheet. But instead of storing one piece of information in each cell, you clump them all together in one cell. You would never do that in spreadsheet.
You should create an item table like this:
+----+--------+--------+
| ID | UserID | ItemID |
+----+--------+--------+
| 1 | 2 | 3 |
| 2 | 2 | 1 |
| 3 | 3 | 3 |
+----+--------+--------+
And possibly another table:
+----+-------------+
| ID | ItemName |
+----+-------------+
| 1 | Mathematics |
| 2 | Jogging |
| 3 | Movies |
+----+-------------+
That'll let you know that User 2 likes Movies and Mathematics, and User 3 likes Movies.
精彩评论