duanmu6231 2011-12-21 01:41
浏览 28

将数据保存为数组或单个字段(php / MySQL)

I am designing a new system for users/clients and I have in my system user preferences. Before I start to create code and the database I want to make sure I do the right thing.

I have these preferences:

  • font size
  • font face
  • font color
  • theme
  • home page
  • dashboard options
  • few true/false options like enable sharing etc...

and more.

My idea was to create each field for each preferences but I thouhgt maybe I can save an object or array instead in a blob.

Is it a good idea?

  • 写回答

2条回答 默认 最新

  • dp518158 2011-12-21 01:58
    关注

    You could make an auxiliary table to keep references of properties names. Then you can link that table with a merge table — between a user id and the id of one of the properties. Doing so, you can always change the properties.

    Using Foreign keys you can also “cascade delete” user details that have a property that does not exist anymore. Furthermore, you can ensure that you add only references to valid property names, and you optimize the search by using indexes.

    Let's say that:

    CREATE TABLE user_preferences_headers
    (
      `id` INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
      `name` VARCHAR(255) NOT NULL
    );
    
    CREATE TABLE `users`
    (
       `id` INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
       `name` VARCHAR(255) NOT NULL,
       `pass` VARCHAR(255) NOT NULL
    );
    
    CREATE TABLE `user_preferences`
    (
      `id_user` INT NOT NULL,
      `id_preference_entity` INT NOT NULL,
      `value` VARCHAR(255)
    );
    
    ALTER TABLE `user_preferences` ADD INDEX ( `id_user` );
    ALTER TABLE `user_preferences` ADD INDEX ( `id_preference_entity` );
    
    ALTER TABLE `user_preferences` ADD FOREIGN KEY ( `id_user` ) REFERENCES `users` (
    `id`
    ) ON DELETE CASCADE ON UPDATE CASCADE ; 
    ALTER TABLE `user_preferences` ADD FOREIGN KEY ( `id_preference_entity` ) REFERENCES `user_preferences_headers` (
    `id`
    ) ON DELETE CASCADE ON UPDATE CASCADE ; 
    

    Now you first select all headers from user_preferences_headers by name, or not, and you use the id to select the desired preference value of a user (identified also by id) from user_preferences. Notice that when you delete an entry in user_preferences_headers, all entries that link to the id of the deleted row will also be deleted.

    评论

报告相同问题?

悬赏问题

  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线