【发布时间】:2018-05-31 07:21:07
【问题描述】:
我正在使用 api-platform 并且我有一个 Book 实体,它与 Writer 具有 ManyToOne 关系。
所有作者都已保存在数据库中,因此我希望能够使用包含绑定到的作者的 POST 请求来创建图书。
但它一直试图坚持一个新的作家。
我怎样才能做到这一点?
编辑:
书籍
/**
*
* @ORM\Entity(repositoryClass="App\Repository\BooksRepository")
* @ApiResource(
* attributes={
* "normalization_context"={"groups"={"read"}}
* }
*
* )
*/
class Books
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\ManyToOne(targetEntity="App\Entity\Property", inversedBy="beans")
* @ORM\JoinColumn(nullable=false)
* @Groups({"read"})
*/
private $property;
public function getProperty(): ?Property
{
return $this->property;
}
public function setProperty(?Property $property): self
{
$this->property = $property;
return $this;
}
}
Writers(也称为属性)
/**
* @ORM\Entity(repositoryClass="App\Repository\PropertyRepository")
*/
class Property
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
* @Groups({"read"})
*/
private $id;
/**
* @ORM\Column(type="string", length=30)
* @Groups({"read"})
*/
private $type;
/**
* @ORM\OneToMany(targetEntity="App\Entity\Books", mappedBy="property", orphanRemoval=true)
* @Groups({"read"})
*/
private $books;
public function __construct()
{
$this->books = new ArrayCollection();
}
public function getId()
{
return $this->id;
}
public function getType(): ?string
{
return $this->type;
}
public function setType(string $type): self
{
$this->type = $type;
return $this;
}
/**
* @return Collection|Books[]
*/
public function getBooks(): Collection
{
return $this->books;
}
public function addBook(Books $book): self
{
if (!$this->books->contains($book)) {
$this->books[] = $book;
$book->setProperty($this);
}
return $this;
}
public function removeBook(Books $book): self
{
if ($this->books->contains($book)) {
$this->books->removeElement($book);
// set the owning side to null (unless already changed)
if ($book->getProperty() === $this) {
$book->setProperty(null);
}
}
return $this;
}
}
【问题讨论】:
-
您能否在答案中添加构建表单(或传递帖子数据)的代码以及使用传递的数据保存一本书的代码?
-
我添加了我得到的所有代码,因为我使用的是 api-platform 并且所有内容都被隐藏了,所以并不多
标签: symfony doctrine api-platform.com