教义一对多关系不会保存 - 违反完整性约束

2022-01-03 00:00:00 php doctrine-orm zend-framework2

我正在尝试使用 Doctrine ORM 关联.我已经阅读了几个教程和在线文档,但它不起作用,老实说,我不确定我在这里做错了什么.似乎我对 Doctrine 的实验非常成功或失败.任何帮助将不胜感激.

I'm attempting to use Doctrine ORM Associations. I've read several tutorials and the online docs, but it's not working, and I'm honestly not sure what I'm doing wrong here. Seems like my experiments with Doctrine are pretty hit or miss. Any assistance would be appreciated.

我想要一个 User 实体和 UserHistory 实体,它有一个用户的多行.这对我来说听起来像是一对多.我不一定需要它是双向的.

I'd like to have a User entity and UserHistory entity, which has multiple rows for a single User. That to me sounds like One-To-Many. I don't necessarily need it to be bidirectional.

我遇到的问题是向用户添加历史记录项会导致保存用户时出错,因为 user_id 列未在 user_history 表中设置.

The problem I'm having is adding a history item to a user results in an error when the user is saved, because the user_id column is not set in the user_history table.

实体:

# EntityUser.php
<?php
namespace ApplicationEntity;

use DoctrineORMMapping as ORM;
use DoctrineCommonCollectionsArrayCollection;

/**
 * @ORMEntity
 */
class User
{
    /**
     * @ORMId
     * @ORMGeneratedValue(strategy="AUTO")
     * @ORMColumn(type="integer")
     */
    protected $id;

    /**
     * @ORMColumn(type="string",length=255)
     */
    protected $username;

    /**
     * @ORMOneToMany(targetEntity="UserHistory", mappedBy="user", cascade={"persist","remove"})
     * @ORMJoinColumn(name="id", referencedColumnName="user_id")
     */
    protected $history;

    public function __construct()
    {
        $this->setHistory(new ArrayCollection());
    }

    public function getHistory()
    {
        return $this->history;
    }
}

# EntityUserHistory.php
<?php
namespace ApplicationEntity;

use DoctrineORMMapping as ORM;

/**
 * @ORMEntity
 * @ORMTable(name="user_history")
 */
class UserHistory
{
    /**
     * @ORMId
     * @ORMGeneratedValue(strategy="AUTO")
     * @ORMColumn(type="integer")
     */
    protected $id;

    /**
     * @ORMManyToOne(targetEntity="User")
     * @ORMJoinColumn(name="user_id", referencedColumnName="id", nullable=false)
     */
    protected $user;

    public function getUser()
    {
        return $this->user;
    }
}

在我的控制器中,我正在尝试:

In my controller, I'm trying this:

    $em = $this->getUserService()->getEntityManager();
    $user = $em->find('PicparaEntityUser', 1);
    $history = new UserHistory();
    $user->getHistory()->add($history);
    $em->persist($user);
    $em->flush();

所有这些都会导致违反完整性约束.

All of which results in an integrity constraint violation.

DoctrineDBALDBALException

DoctrineDBALDBALException

文件:/myproject/vendor/doctrine/dbal/lib/Doctrine/DBAL/DBALException.php:91

File: /myproject/vendor/doctrine/dbal/lib/Doctrine/DBAL/DBALException.php:91

留言:

使用参数 [null] 执行INSERT INTO user_history (user_id) VALUES (?)"时发生异常:

An exception occurred while executing 'INSERT INTO user_history (user_id) VALUES (?)' with params [null]:

SQLSTATE[23000]:违反完整性约束:1048 列user_id"不能为空

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

就像我说的那样,我在 SO 上四处挖掘,用谷歌搜索,尝试在注释中移动内容.这是我所得到的.不知道我做错了什么.有人可以帮忙吗?

Like I said, I've dug around here on SO, googled, tried moving things around in the annotations. This is as far as I get. Not sure what I'm doing wrong. Can anyone help?

推荐答案

问题是您没有在历史类中设置用户实体.关联的东西不会自动执行此操作.

The problem is that you are not setting the user entity in your history class. The association stuff does not do this automatically.

class UserHistory
{
    public function setUser($user) { $this->user = $user; }

class User
{
    public function addHistory($history)
    {
        $this->history->add($history);
        $history->addUser($this);  // *** This is what you are missing
    }

// In your controller class
$user->addHistory($history);

相关文章