douliao8318 2015-03-11 03:47
浏览 24

更新或检索数据库中的行的最佳方法是什么?

I refered to Wordpress' database to create config setting for my app in Laravel. I created a app_settings table with id, setting_name and setting_value as columns to store each config name and value in rows. It works fine but the problem occurs whenever I retrieve or update data.

$appsetting = new AppSetting();
return $appsetting->all();

When I query the database it returns me a json like:

[
{
    "id": 37,
    "setting_name": "site_name",
    "setting_value": "Title",
    "created_at": "2015-03-09 10:40:35",
    "updated_at": "2015-03-11 03:23:48"
},
{
    "id": 38,
    "setting_name": "site_url",
    "setting_value": "http://localhost:800",
    "created_at": "2015-03-09 10:40:35",
    "updated_at": "2015-03-11 03:23:48"
},
{
    "id": 39,
    "setting_name": "site_admin",
    "setting_value": "local@host.com",
    "created_at": "2015-03-09 10:40:35",
    "updated_at": "2015-03-11 03:23:48"
}
]

Case 1:

Whenever I had to use a variable I had to remember the column index to get it's value. Eg. $settings[0]['setting_value'] to retrieve Titleand this make code pretty much static than using something like $settings['site_name'].

Case 2:

If I had to update multiple settings at once, I had to use multiple update commands with where clause.

$appsetting::where('setting_name', '=', 'site_name')->update(['setting_value' => $setting['title']]);

$appsetting::where('setting_name', '=', 'site_url')->update(['setting_value' => $setting['url']]);

$appsetting::where('setting_name', '=', 'site_admin')->update(['setting_value' => $setting['email']]);

What are the best way to update or retrieve rows in database in this case?

I want output like this while using attributes like site_title in rows

[{
    "site_title"    : "Title",
    "site_url"      : "http://localhost",
    "site_admin"    : "local@host"
}]
  • 写回答

3条回答 默认 最新

  • duandou2763 2015-03-11 04:06
    关注
    $output = array();
    foreach ($settings as $setting) {
     $output[] = array($setting['setting_name'] => $setting['setting_value']);
    }
    return json_encode($output);
    
    评论

报告相同问题?

悬赏问题

  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害