[英]Doctrine & Symfony3 OneToOne relations, inverse side does not exist
[英]doctrine replace onetoone relation from inverse side
我有兩個實體Product
和Print
具有一對一的關系,其中Product
是父實體, Print
是子實體,但“擁有方”是Print
(在數據庫print
表中將有product_id
和外鍵)
產品:
<?php
declare(strict_types=1);
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity()
*/
class Product
{
/**
* @ORM\Id()
* @ORM\Column(type="integer")
*/
public int $id;
/**
* @ORM\Column(type="string", length=100)
*/
public string $name;
/**
* @ORM\Column(type="text")
*/
public string $description;
/**
* @ORM\Column(type="boolean")
*/
public bool $available;
/**
* @ORM\OneToOne(targetEntity="Print", mappedBy="product", cascade={"persist", "remove"}, orphanRemoval=true)
*/
public Print $print;
public function __construct(
int $id,
string $name,
string $description,
bool $available,
) {
$this->id = $id;
$this->name = $name;
$this->description = $description;
$this-available = $available;
}
public function udpate(
string $name,
string $description,
bool $available,
Print $print,
) {
$this->name = $name;
$this->description = $description;
$this-available = $available;
$this->replacePrint($$print);
}
public function replacePrint(Print $print): void
{
$this->print = $print;
}
}
和打印:
<?php
declare(strict_types=1);
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity()
*/
class Print
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
public int $id;
/**
* @ORM\Column(type="string")
*/
public array $key;
/**
* @ORM\Column(type="string")
*/
public array $value;
/**
* @ORM\OneToOne(targetEntity="Product", inversedBy="print")
* @ORM\JoinColumn(name="product_id", referencedColumnName="id", nullable=false)
*/
public Product $product;
public function __construct(Product $product, string $key, string $value)
{
$this->product = $blueprint;
$this->key = $key;
$this->value = value;
}
}
當我插入新產品時一切都很好
$product = new Product($id, $name, $description, $available);
$product->replacePrint(new Print($product, $key, $value));
$em->persist($product);
$em->flush
它正在插入產品和相關的印刷品,為印刷品生成新的 id
但是現在當我想更新產品時:
$product = $em->find(Product::class, $id);
$product->udpate($name, $description, $available);
$product->replacePrint(new Print($product, $key, $value));
$em->persist($product);
$em->flush
我收到錯誤Cannot assign null to property App\\Entity\\Print::$id of type int
您必須保留 New Print 實體:
$product = $em->find(Product::class, $id);
$product->udpate($name, $description, $available);
$print = new Print($product, $key, $value);
$product->replacePrint($print);
$em->persist($print);
$em->persist($product);
$em->flush();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.