gpt4 book ai didi

php - 如何取消设置克隆的 PHP 对象的 ID

转载 作者:可可西里 更新时间:2023-11-01 00:28:41 24 4
gpt4 key购买 nike

我正在从事一个使用 Docrtrine 和 Symfony 2.7 的项目。我有一个要克隆的文档实体,当然我需要确保我没有重复的主键。到目前为止,这是我尝试过的:

/**
* Document
*
* @ORM\Table(name="documents")
*/
class Document {
public function ___clone(){
$newObj = clone $this;
$newObj->id = null;
return $newObj;
}
...
}

这似乎并没有太大作用,但是,当我调用 clone myDocument 然后尝试坚持时,我仍然收到此消息:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1' for key 'UNIQ_A2B07288ECC6147F'

如何让对象的主键恢复为空或自动递增状态?

=====

更新:使用

public function __clone(){
$this->id = null;
}

仍然会导致相同的错误。完整的错误文本:

An exception occurred while executing 'INSERT INTO documents (usageFrom, usageTo, status, workflow_identifier, created_date, modified_date, language_id, translationRoot_id, ownerGroup_id, responsibleUser_id, production_id, media_id, created_user, modified_user) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)' with params ["2018-06-28 09:54:37", "2018-06-28 09:54:37", 100, "4cc723c2a5730c1b9c2ed6428ae57205", "2018-06-28 09:54:37", "2018-06-28 09:54:37", null, null, null, null, 1, null, 1, 1]:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1' for key 'UNIQ_A2B07288ECC6147F'

最佳答案

这不是怎么来的PHP’s cloning作品。将 __clone 视为 __construct。在 __clone 方法中,您必须将新值分配给 $this

class Document 
{
public function ___clone()
{
// simple as that
$this->id = null;
}
}

在您当前的代码中,$newObj 将被丢弃,而克隆的对象仍具有原始 ID。

此外,如果您想创建深拷贝,请记住在您的 __clone 方法中克隆子对象,否则您最终会得到两个引用相同子对象的实体。 (或者,在持久化/重新加载之后:其中一个实体将失去其子实体。)

关于php - 如何取消设置克隆的 PHP 对象的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51080660/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com