duanqian9593 2013-11-15 04:02
浏览 62
已采纳

是否可以更改Doctrine对象的类?

Im using Doctrine and I need to clone an object.

Two tables in the database have the same columns, but one exists for backlog orders whilst one is confirmed orders. Probably not the best way to do it, but they must be seperate as certain foreign keys cannot be satisfied on backlog objects.

So, I need to clone one object from the backlog and insert it into the current orders table. But if I clone the backlog order object, it will set the class to backlog order.

$backlog_orders = $this->Subscription_model->getBacklogOrders();
foreach($backlog_orders as $backlog_order){
    $new_order = new Entities\NewOrder;
    $new_order = clone $backlog_order;
    //Do other stuff to new order
    //At this point, I need to change the class of the object to NewOrder so that it will insert it into the correct table
    echo get_class($order); // Outputs BacklogOrder
    $this->Subscription_model->updateOrder($order); // Saves to DB
}
  • 写回答

2条回答 默认 最新

  • dp6319 2013-11-15 04:11
    关注

    First I'd like to point out a mistake in your question, which kind of explains why you run into this.

    "But if I clone the backlog order object, it will set the class to backlog order."

    Nothing gets set, in this point in your code..

    $new_order = new Entities\NewOrder;
    $new_order = clone $backlog_order;
    

    ..you first make a $new_order object and then make a new $new_order object which is a clone of $backlog_order. In other words, the first line with new Entities\NewOrder means absolutely nothing.

    You also should know that the clone keyword in PHP makes a shallow copy. So all the references in $new_order are still to the old order. Even if you would manage to change the class in the way you are trying it right now doctrine would not do an insert but rather an update.

    What you basically want is to make a true copy, which is not provided by PHP because it would violate the type system. In order to do this you should just fill $new_order with all the data from $backlog_order.

    You should however also consider that you probably have an auto incrementing primary key right now. I don't know if doctrine will let you override this.

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

报告相同问题?