[英]Symfony 3 OneToMany relationship error
我正在嘗試創建一個OneToMany表單,並且symfony探查器會引發實體錯誤,這是代碼:
Tasks.php
<?php
namespace ShopBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
*
*
* @ORM\Entity
* @ORM\Table(name="task")
*/
class Tasks
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\Column(type="string", nullable=true,length=100)
*
*/
protected $description;
/**
* @ORM\OneToMany(targetEntity="ShopBundle\Entity\Tags", cascade={"all"}, mappedBy="name")
*/
protected $tags;
public function __construct()
{
$this->tags = new ArrayCollection();
}
public function getId()
{
return $this->id;
}
public function setId($id)
{
$this->id = $id;
}
public function getDescription()
{
return $this->description;
}
public function setDescription($description)
{
$this->description = $description;
}
public function getTags()
{
return $this->tags;
}
public function addTag(Tags $tag)
{
$this->tags->add($tag);
}
public function removeTag(Tags $tag)
{
$this->tags->removeElement($tag);
}
}
這是Tags.php
<?php
namespace ShopBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
*
* @ORM\Entity
* @ORM\Table(name="tag")
*/
class Tags
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\ManyToOne(targetEntity="ShopBundle\Entity\Tasks", inversedBy="tags")
* @ORM\JoinColumn(name="task")
*/
protected $name;
public function getId()
{
return $this->id;
}
public function setId($id)
{
$this->id = $id;
}
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
}
探查器拋出2個錯誤:關聯ShopBundle \\ Entity \\ Tasks#tags引用擁有方字段ShopBundle \\ Entity \\ Tags#name,該字段未定義為關聯,而是字段。
和
關聯ShopBundle \\ Entity \\ Tasks#tags指的是不存在的擁有方字段ShopBundle \\ Entity \\ Tags#name。
它將數據保存到數據庫中,但是我無法從數據庫中獲取數據
首先檢查調試CLI告訴您什么:
php bin/console doctrine:schema:validate
看看Doctrine docs 一對多,雙向的示例
在Tags@JoinColumn
您還應該在實體Tasks
添加要與之連接的字段的字段名稱。 ( referencedColumnName
)
還可以看到$name
不是一個字段,您想在其中保留此映射的實體? 嘗試添加另一個帶有實體名稱的字段,而不是在$name
之前添加注釋(順便說一句,期望標記名稱也會誤導,但會得到Entity Task
)。
例如 :
// Tags.php
/**
* @ManyToOne(targetEntity="ShopBundle\Entity\Tasks", inversedBy="tags")
* @JoinColumn(name="task_id", referencedColumnName="id")
*/
protected $task;
然后記住還要在Tasks
實體中更改映射:
// Tasks.php
/**
* @ORM\OneToMany(targetEntity="ShopBundle\Entity\Tags",
* cascade={"all"}, mappedBy="task")
*/
protected $tags;
最后更新您的架構:
php bin/console doctrine:schema:update --force
希望能幫助到你
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.