dsfsdf7852 2015-01-26 23:07 采纳率: 100%
浏览 57
已采纳

如何确定UPDATE动态查询中应包含哪些属性?

Figure1: Here's an example Model class

class Games {
    public $id = 0;
    public $date = null;
    public $player1_id = 0;
    public $player2_id = 0;
    public $score = null;

    public function save(){
        if(empty($this->id)){
            // do INSERT here
        }
        else{
            // do UPDATE here  
        }
    }
}

Figure2: Here's an example use of the class

// Save a new date to an existing game
$game = new Games;
$game->id = $input['id'];
$game->date = $input['date'];
$game->save();

If an UPDATE query is performed based on figure2, then the values for player1_id, player2_id, and score will be incorrectly overwritten to zeros/nulls. Therefore, I need a way to determine from inside the class that certain properties were not set from the call in figure2, so I can dynamically alter the UPDATE query to only update specific fields in the database. Or am I approaching this wrong?

Note: I know I could use a single array property to hold all the fields (and use isset), but this feels like it's breaking the point of the Model and would also be very PHP specific (in that the solution doesn't transfer nicely to other languages such as JAVA where arrays are strictly typed?). I also realize I could do what I think ORMs do and make an initial SELECT query before I perform an update (but that seems very inefficient!)

  • 写回答

3条回答 默认 最新

  • dongyun7571 2015-01-27 03:00
    关注
    1. declare a PRISTINE constant. Try setting it to new instance of an object you've made, say new MyPristine.
    2. In your Game constructor, set all fields to that constant. This is the trick to mark them as " untouched ". You can use Reflection ( like ReflectionClass($game)->getProperties() ) to loop through all of them
    3. Before saving, loop again through the fields and test their value with PRISTINE. If it's different, it needs to be changed.

    This solution suppose no one/nothing else will change the Game instances between the steps 2 and 3. That's why most ORMs will do a SELECT beforehand.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题