교리-관계를 통해 새로운 실체가 발견되었습니다.
2 주 이후 새 요소를 플러시하는 동안이 문제가 발생했습니다.
위험 : Doctrine \ ORM \ ORMInvalidArgumentException :
엔티티에 대한 지속 조작을 계단식으로 구성하지 않은 관계 'Comment # capture'를 통해 새 엔티티가 발견되었습니다.
그러나은 capture
이미 데이터베이스에 있으며으로 가져옵니다 findOneBy
. 따라서 연속적으로 지속하거나 지속하면
테이블 제약 위반 : 중복 항목.
주석은 새 캡처 및 모든 필수 필드가 설정된 다른 캡처를 사용하여 루프에서 생성됩니다.
모든 엔터티가 지속되고 /되거나 a findOne
(및 모두 유효한)에 의해 획득 되었더라도 플러시가 여전히 실패합니다.
나는이 문제를 오랫동안 다루고 있으므로 제발 도와주세요
나는 똑같은 문제가 있었고 똑 같았다 EntityManager
. 관련 개체를 삽입하고 싶었습니다 ManyToOne
. 그리고 나는 cascade
persist
.
예 :
$category = $em->find("Category", 10);
$product = new Product();
$product->setCategory($category)
$em->persist($product);
$em->flush();
이것은 나에게 동일한 예외를 던집니다.
그래서 해결책은 다음과 같습니다.
$category = $em->find("Category", 10);
$product = new Product();
$product->setCategory($category)
$em->merge($product);
$em->flush();
제 경우에는 너무 이른 전화
$this->entityManager->clear();
문제를 일으켰습니다. 또한 최근 개체에 대한 클리어 만 수행하여 사라졌습니다.
$this->entityManager->clear($capture);
내 대답은 주제와 관련이 있지만 특정 경우에는별로 관련이 없으므로 위의 답변이 도움이되지 않았으므로 인터넷 검색을하는 사람들에게는 이것을 게시합니다.
제 경우에는 관계가 있고 해당 관계가 매우 동일한 엔터티로 설정된 일괄 처리 엔터티와 동일한 오류가 발생했습니다.
내가 잘못한 것 :
$this->entityManager->clear();
엔티티 배치를 처리하는 동안 수행 하면 다음 엔티티 배치가 분리 된 관련 엔티티를 가리 키기 때문에이 오류가 발생합니다.
잘못된 점 :
리포지토리의 모든 엔티티를 분리
$this->entityManager->clear();
하는 것과 동일하게 작동 하는지 몰랐습니다$this->entityManager->detach($entity);
.나는 그것이
$this->entityManager->clear();
또한 관련 엔티티를 분리 한다고 생각했습니다 .
내가해야 할 일 :
엔티티를 반복하고 하나씩 분리해야합니다. 그러면 미래 엔티티가 가리키는 관련 엔티티가 분리되지 않습니다.
누군가에게 도움이되기를 바랍니다.
우선, 코드를 더 잘 관리해야합니다. 엔티티와 컨트롤러에 3 개의 다른 들여 쓰기가있는 것처럼 보입니다. 이것은 읽기 어렵고 Symfony2 코딩 표준에 맞지 않습니다 .
컨트롤러에 대해 표시 하는 코드 가 완전하지 않으며 어디에서 오는지 알 수 없습니다 $this->activeCapture
. 당신 안에는 내가 생각 $people['capture']
하는 Capture
물건 이 들어 있는 것이 있습니다 . 이건 매우 중요합니다.
Capture in $people['capture']
이 지속되거나 다른 EntityManager에서 가져 오는 경우 $this->entityManager
(다시 말해 어디에서 왔는지 알 수 없음) Doctrine2는 개체가 이미 지속되고 있는지 알지 못합니다.
모든 작업에 대해 Doctrine Entity Manager의 동일한 인스턴스를 사용해야합니다 ( spl_object_hash
EM 개체에서 사용하여 동일한 인스턴스인지 확인).
Capture 개체로 수행 할 작업을 EntityManager에 알릴 수도 있습니다.
// Refreshes the persistent state of an entity from the database
$this->entityManager->refresh($captureEntity);
// Or
// Merges the state of a detached entity into the
// persistence context of this EntityManager and returns the managed copy of the entity.
$captureEntity = $this->entityManager->merge($captureEntity);
이것이 도움이되지 않으면 더 많은 코드를 제공해야합니다.
오류 : 엔터티에 대한 지속 작업을 계단식으로 구성하지 않은 'Comment # capture'
문제 :
/**
* @ORM\ManyToOne(targetEntity="Capture", inversedBy="comments")
* @ORM\JoinColumn(name="capture_id", referencedColumnName="id",nullable=true)
*/
protected $capture;
캐스케이드 지속을 구성하지 않았습니다.
이것을 시도하십시오 :
/**
* @ORM\ManyToOne(targetEntity="Capture", inversedBy="comments", cascade={"persist", "remove" })
* @ORM\JoinColumn(name="capture_id", referencedColumnName="id",nullable=true)
*/
protected $capture;
문제의 엔티티를 새로 고치는 것이 제 경우에 도움이되었습니다.
/* $item->getProduct() is already set */
/* Add these 3 lines anyway */
$id = $item->getProduct()->getId();
$reference = $this->getDoctrine()->getReference(Product::class, $id);
$item->setProduct($reference);
/* Original code as follows */
$quote->getItems()->add($item);
$this->getDoctrine()->persist($quote);
$this->getDoctrine()->flush();
Despite my $item
already having a Product
set elsewhere (turns out it was set via a different instance of EntityManager
), I was still getting the error.
So this is a hack of sorts, by retrieving id
of the existing product, and then retrieving a reference of it, and using setProduct
to "refresh" the whatever connection. I later fixed it by ensuring to have only a single instance of EntityManager
in my code.
I got this error too when tried to add new entity.
A new entity was found through the relationship 'Application\Entity\User#chats'
that was not configured to cascade persist operations for entity: ###.
To solve this issue: Either explicitly call EntityManager#persist() on this unknown entity or
configure cascade persist this association in the mapping for example @ManyToOne(..,cascade={"persist"}).
My case was that I tried to save entity, that shouldn't be saved. Entity relations was filled and tried to be saved (User
has Chat
in Many2Many, but Chat was a temporary entity), but there were some collisions.
So If I use cascade={"persist"}
I get unwanted behaviour - trash entity is saved. My solution was to remove non-saving entity out of any saving entities:
// User entity code
public function removeFromChats(Chat $c = null){
if ($c and $this->chats->contains($c)) {
$this->chats->removeElement($c);
}
}
Saving code
/* some code witch $chat entity */
$chat->addUser($user);
// saving
$user->removeFromChats($chat);
$this->getEntityManager()->persist($user);
$this->getEntityManager()->flush();
'program story' 카테고리의 다른 글
Android ViewPager는 현재보기를 가져옵니다. (0) | 2020.11.17 |
---|---|
C에서 sizeof 연산자는 2.5m를 통과하면 8 바이트를 반환하지만 1.25m * 2를 통과하면 4 바이트를 반환합니다. (0) | 2020.11.17 |
요소를 따라 목록을 하위 목록으로 분할 (0) | 2020.11.17 |
형식 내부에 열거 형 사용-컴파일러 경고 C4482 C ++ (0) | 2020.11.17 |
자바 스크립트에 지연 추가 (0) | 2020.11.17 |