私はこれについて多くのことを検索しました、そして真剣に尋ねることは私の最後のリソースです、教義は私を激しく蹴っています。
「Contract」という名前のエンティティと別の「Request」があります。契約には複数のリクエストがある場合があります。新しいリクエストを追加するときに、そのクライアントの既存のコントラクトを検索し、すでに存在する場合は関連付け、存在しない場合は作成します。
RequestRepository.phpの場合:
public function findOrCreate($phone)
{
$em = $this->getEntityManager();
$contract = $this->findOneBy(array('phone' => $phone));
if($contract === null)
{
$contract = new Contract();
$contract->setPhone($phone)
->setDesDate(new \DateTime());
# save only if new
$em->persist($contract);
}
return $contract;
}
問題は、コントラクトが新しい場合は問題なく機能しますが、dbから「再利用」された場合はその属性を変更できません。私はすでにOneToManyとManyToOneをチェックしました。
Contract.phpの場合:
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
* @ORM\OneToMany(targetEntity="Request", mappedBy="contract")
*/
private $id;
Request.phpの場合:
/**
* @var string
*
* @ORM\JoinColumn(nullable=false)
* @ORM\ManyToOne(targetEntity="Cid\FrontBundle\Entity\Contract", inversedBy="id", cascade={"persist"})
*/
protected $contract;
Contract.php内の属性を変更するメソッドもあります。
public function addTime($months)
{
$days = $months * 30;
$this->des_date->add(new \DateInterval("P".$days."D"));
return $this;
}
リクエストを作成し、コントラクトを「findOrCreate」しますが、後者が「フレッシュ」でない場合、addTimeはdbに保存されません。
私は何が間違っているのですか?
編集:コントローラーは、マイナーな変更を加えた一般的なCRUDです。
「リクエスト」の名前の衝突について心配する必要はありません。実際のコードはスペイン語です。リクエスト=要請=
public function createAction(Request $req)
{
$entity = new Request();
$form = $this->createForm(new RequestType(), $entity);
$form->bind($req);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$entity->setUser($this->getUser());
$data = $request->request->get('cid_frontbundle_requesttype');
$phone = $data['phone_number'];
$reqRep = $em->getRepository('FrontBundle:Request');
$entity = $reqRep->newRequest($entity, $phone);
return $this->redirect($this->generateUrl('request_show', array('id' => $entity->getId())));
}
return $this->render('FrontBundle:Request:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
newRequest:
public function newRequest($request, $phone)
{
$em = $this->getEntityManager();
$contractRep = $em->getRepository('FrontBundle:Contract');
$contract = $contractRep->findOrCreate($phone);
$contract->addTime(123); # this is the problem, I use var_dump and this method works, but doesn't persists
$em->persist($request);
$em->flush();
return $request;
}