【问题标题】:Multiple entities persist doctrine2 Zend多个实体坚持原则2 Zend
【发布时间】:2012-09-10 03:45:11
【问题描述】:

我有 3 个实体 Users、UserProfile 和 Staffs

用户配置文件通过用户 ID 链接到用户表 Staff 表使用 userprofileid 链接到 userprofile

管理员创建用户配置文件并生成注册号、用户名和密码。

我想将用户记录添加到用户表,然后添加用户个人资料,然后将个人资料 ID 添加到员工表。

我想按顺序保存三个实体

我尝试为喜欢的用户创建一个实例

$this->userent->setUsername('xxx');
$this->em->persist($this->userent);
$this->em->flush();

然后:

$this->profileent->setFirstname('xxx');
$this->em->persist($this->profileent);
$this->em->flush();

基本上三个实体之间共享一个表单,我想顺序插入三个表,

更新

除了users 实体之外,我还有一个链接到用户的usertype 实体...我只想保留外键。我有

setUserType(Usertype $userType)方法是users中user_type实体的一个实例

当我这样做时

 $this->userent = new Users();
$this->userent->setUserType($this->em->getRepository('\Campus\Entity\Usertype')->findByUserType("admin")) 

我得到了错误

Argument 1 passed to Campus\Entity\Users::setUserType() must be an instance of Campus\Entity\Usertype, array given

如果我传递作为 Usertype 实例的数组的值

我收到一条错误消息,说需要 ArrayCollection..help 的数组!!!

Argument 1 passed to Doctrine\Common\Collections\ArrayCollection::__construct() must be of the type array, object given, called in D:\xampp\htdocs\zend\library\Doctrine\ORM\UnitOfWork.php on line 406 defined in D:\xampp\htdocs\zend\library\Doctrine\Common\Collections\ArrayCollection.php on line 46

【问题讨论】:

  • 我其实很想知道如何坚持多个实体..

标签: php doctrine-orm


【解决方案1】:

少考虑数据库,多考虑对象。这就是教义的全部意义所在。

你想要这样的东西:

<?php
// create some entities

$user = new Entity\User();
$user->setUsername('userman');

$profile = new Entity\UserProfile();
$profile->setFirstname('joe');
$profile->setLastname('smith');

$staff = new Entity\Staff();
$staff->setSomething('value-for-something');

// associate those entities together
$profile->setStaff($staff);
$user->setProfile($profile);

// assuming you have set up cascade={"persist"} on your associations
$this->em->persist($user);

// if you haven't set up cascade={"persist"}, you will need to call persist on each entity:
// $this->em->persist($profile);
// $this->em->persist($staff);

$em->flush();

所以,基本的想法是你构建你的对象,将它们放入 Doctrine 的工作单元(通过调用 persist() 并可能设置一些级联),然后在单个事务中将它们全部写入数据库通过调用flush()

【讨论】:

  • 嗨,蒂姆,我认为这应该可行,我还查看了一篇关于 Hibernate 的与此解决方案类似的文章...您能否查看更新的部分...我有外键问题...你能帮忙吗..
【解决方案2】:

你可以持久化每个实体,最后再flush()一次。

如果你的实体之间有关系,你可以检查下面的注释

cascade={"persist"}

“级联将操作持久化到关联实体。”

在这里查看文档:http://docs.doctrine-project.org/en/2.0.x/reference/working-with-associations.html#transitive-persistence-cascade-operations

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-06
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多