douxia1988 2016-11-30 13:56
浏览 183
已采纳

将MySQL查询字段作为数组处理是否有意义?

I have a php object method that load object "A" with the following MySQL query:

SELECT A.foo, A.bar...

I have another php object named B that uses MySQL fields from object A:

SELECT A.foo, A.bar...
       B.abc, B.xyz

To prevent code repetition, would it be considered a good practice to create an array (or an object) that stores the MySQL fields names of Object A so that this array can be used in object A and object B, like this:

Object A MySQL loading:

SELECT '.implode(',', $mysql_a_fields).' '...

Object B MySQL loading:

SELECT '.implode(',', $mysql_a_fields).', 
        B.abc, B.xyz

Or would it be code smell?

The goal is to to prevent repeating some SQL fields along queries that use those SQL fields. For example, if there is a mysql date field for object A that I want to get formatted the same way in all the requests I use this date field, is there any design pattern to prevent repeating DATE_FORMAT(date_field) in all the request?

Thank you

  • 写回答

1条回答 默认 最新

  • doupeng6890 2016-11-30 16:19
    关注

    About that array of field names. I would not do it. If you need to write all your selects this way, than write them. I do not know enough about your class/project structure to say if this makes sense.

    To help you with your date formatting problem (well, it's not really a problem, isn't it), I think you have two options: 1. Get the date field from the database as is and convert it in PHP. (Use a helper class that is accessible from everywhere to do this.) 2. Create a stored procedure that converts the format for you and use this in your SELECT queries.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 电脑拓展屏桌面被莫名遮挡
  • ¥20 ensp,用局域网解决
  • ¥15 Python语言实验
  • ¥15 我每周要在投影仪优酷上自动连续播放112场电影,我每一周遥控操作一次投影仪,并使得电影永远不重复播放,请问怎样操作好呢?有那么多电影看吗?
  • ¥20 电脑重启停留在grub界面,引导出错需修复
  • ¥15 matlab透明图叠加
  • ¥50 基于stm32l4系列 使用blunrg-ms的ble gatt 创建 hid 服务失败
  • ¥150 计算DC/DC变换器平均模型中的参数mu
  • ¥25 C语言代码,大家帮帮我
  • ¥15 请问以下文字内容及对应编码是用了什么加密算法或压缩算法呢?