我有两个实体页面和文件。一页有许多文件。我的其他实体也有很多文件,因此我通过两列(entity_id 和entity_type)将页面和文件连接起来。当我有样本数据并且得到它时,一切正常。当我尝试将页面和文件添加到数据库时,我发现问题,文件从页面获取 ID,但没有获取实体类型。
创建实体:
$page = new \CmsIr\Page\Entity\Page();
$page->exchangeArray($form->getData());
$page->setEntityType('page');
$this->getEm()->persist($page);
$this->getEm()->flush();
foreach($scannedDirectory as $file) {
$mimeType = $this->getFileService()->getMimeContentType($this->uploadDir . '/' . $file);
$pageFile = new \CmsIr\File\Entity\File();
$pageFile->setFilename($file);
$pageFile->setPage($page);
$pageFile->setMimeType($mimeType);
$this->getEm()->persist($pageFile);
$this->getEm()->flush();
}
错误看起来像:
An exception occurred while executing 'INSERT INTO cms_file (entity_type, entity_id, filename, mime_type) VALUES (?, ?, ?, ?)' with params [null, 5, "140343_las-promienie-slonca-56c9a66d27830.jpg", "image\/jpeg; charset=binary"]:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'entity_type' cannot be null
页面:
/**
* @ORM\Entity
* @ORM\Table(name="cms_page")
*/
class Page
{
/**
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
* @ORM\Column(type="integer")
*/
protected $id;
/** @ORM\Column(type="string") */
protected $name;
/** @ORM\Column(type="string") */
protected $subtitle;
/** @ORM\Column(type="string") */
protected $url;
/** @ORM\Column(type="string") */
protected $entity_type;
/**
* @ORM\OneToOne(targetEntity="CmsIr\System\Entity\Status")
* @ORM\JoinColumn(name="status_id", referencedColumnName="id")
*/
protected $status;
/** @ORM\Column(type="text") */
protected $content;
/** @ORM\Column(type="string") */
protected $filename;
/**
* @ORM\OneToMany(targetEntity="CmsIr\File\Entity\File", mappedBy="page")
*/
protected $files;
public function __construct()
{
$this->files = new \Doctrine\Common\Collections\ArrayCollection();
}
文件:
/**
* @ORM\Entity
* @ORM\Table(name="cms_file")
*/
class File
{
/**
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
* @ORM\Column(type="integer")
*/
protected $id;
/** @ORM\Column(type="string") */
protected $entity_type;
/** @ORM\Column(type="integer") */
protected $entity_id;
/** @ORM\Column(type="text") */
protected $filename;
/** @ORM\Column(type="string") */
protected $mime_type;
/**
* @ORM\ManyToOne(targetEntity="CmsIr\Page\Entity\Page")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="entity_id", referencedColumnName="id"),
* @ORM\JoinColumn(name="entity_type", referencedColumnName="entity_type"),
* })
**/
protected $page;
最佳答案
从您的Page
实体定义中可以看出,entity_type
被定义为integer
:
/** @ORM\Column(type="integer") */
protected $entity_type;
在您的代码片段中:
$page->setEntityType('page');
您正在传递一个字符串值。
我的解决方案是获取您尝试设置的 entity_type
的引用,就像调用 setter 方法之前一样。
本质上,您的 setter 方法应该接受 entity_type
实体的实例,即对象而不是字符串。
希望这至少能为您指明正确的方向。
关于php - 学说 2 @joincolumns,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35535975/