php - 无法将值插入到 OneToOne 关系中的 Doctrine 2 中的映射列

标签 php zend-framework doctrine-orm zend-framework2 doctrine

我对 Doctrine 还很陌生,在一种情况下需要帮助。我有 2 个简单的表专辑和流派。请检查以下结构:

专辑

id | title   | genre_id | createdon
1  | Album 1 | 1        | 21/05/2015
2  | Album 2 | 2        | 21/05/2015

类型

id | genre   | active
1  | Pop     | 1
2  | Blue    | 1
3  | Rock    | 1
4  | Country | 1
专辑表中的

genre_id 映射到流派表的 id 列。

在相册实体中,我已通过以下过程映射了它:

/**
 * @ORM\OneToOne(targetEntity="Genre", mappedBy="albums")
 * @ORM\JoinColumn(name="genre_id", referencedColumnName="id")
 **/
private $genre;

public function getGenre(){
    return $this->genre;    
}

public function setGenre($value)
{
    $this->genre = $value;
    return $this;
}

我可以通过 getGenre() 方法完美地获取流派名称,但问题是在将值插入数据库时​​。我需要插入类型_id,它是一个整数值,但在从 Controller 调用 setGenre() 方法后,我收到以下错误:

Expected value of type "Album\Entity\Genre" for association field "Album\Entity\Albums#$genre", got "string" instead.

我还尝试指定另一个私有(private)变量,例如原始列名称,即genre_id,如下所示:

/** @ORM\Column(type="integer") */
protected $genre_id;

public function setGenre($value)
{
   $this->genre_id = $value;
   return $this;
}

但是我收到以下错误:

An exception occurred while executing 'INSERT INTO Albums (title, createdon, genre_id) VALUES (?, ?, ?)' with params ["nfhgfh", "21/05/2015", null]:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'genre_id' cannot be null

我从 Controller 调用实体,如下所示:

$albums = new Albums();
$albums->setTitle($postData['title']);
$albums->setGenre($postData['genre_id']);
$albums->setCreatedon(date('d/m/Y'));
$this->em()->persist($albums);

$this->em()->flush();

我严重陷入这个问题,需要你的帮助。我不知道它如何获得空值。请帮忙。

最佳答案

通过 id 查询流派对我有用。请在 Controller 中找到下面我更新的代码:

$albums = new Albums();
$albums->setTitle($postData['title']);
$albums->setCreatedon(date('d/m/Y'));

$genre = $this->em()->find('Album\Entity\Genre', $postData['genre_id']);

$albums->setGenre($genre);
$this->em()->persist($albums);

$this->em()->flush();

这是您指定的流程吗?感谢您的帮助。

关于php - 无法将值插入到 OneToOne 关系中的 Doctrine 2 中的映射列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30372647/

相关文章:

symfony - 在 Doctrine2 中为 FormBuilder 中使用的元表结构创建映射

php - OpenAI 将 API 代码从 GPT-3 转换为 chatGPT-3.5

php - 将 int 转换为 RGB。 PHP 和 HTML/CSS 中的可视化

zend-framework - 最佳实践 : Zend View: Load content from database and render PHP-code included in content

php - Symfony2,学说限制和偏移量没有按预期工作

php - 将 Symfony 实体导出为 CSV

php - Socket.io 和 Phalcon PHP

php - 这个无法访问的区域是否可以仅使用 CSS 进行链接?

php - 对 Zend 查询生成器的 SQL 查询(OR、AND、ORDER BY FIELD、IS NULL)

php - Zend_Navigation 的自定义渲染