'被认证' 我已经得到了以下型号:Doctrine2:PDOException [23000]:SQLSTATE [23000]:完整性约束违规:1062重复条目键 '名'
UserStatus:
<?php
namespace Base;
/** @Entity @Table(name="user_status") */
class UserStatus extends \Skeleton\Base {
/**
* @Id @Column(type="integer")
* @GeneratedValue(strategy="AUTO")
*/
protected $id;
/** @Column(length="256") */
protected $name;
/**
* @OneToMany(targetEntity="Base\User", mappedBy="Status")
*/
protected $Users;
}
用户:
<?php
namespace Base;
/**
* @Entity
* @Table(name="user")
* @InheritanceType("JOINED")
* @DiscriminatorColumn(name="discriminator", type="string")
* @DiscriminatorMap({
* "admin" = "Administrator",
* "participant" = "Participant",
* "employee" = "Employee"
* })
*/
class User extends \Skeleton\Skeleton implements Interfaces\User {
/**
* @Id @Column(type="integer")
* @GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ManyToOne(targetEntity="UserStatus", inversedBy="Users")
* @JoinColumn(name="status_id", referencedColumnName="id")
*/
protected $Status;
/** @Column(length=255) */
protected $username;
/** @Column(length=255) */
protected $password;
/** @Column(length=255) */
protected $firstname;
/** @Column(length=128) */
protected $insertion;
/** @Column(length=255) */
protected $lastname;
/** @Column(type="datetime") */
protected $created;
/** @Column(type="integer", name="creator_id") */
protected $Creator;
/** @Column(type="datetime") */
protected $modified;
/** @Column(type="integer", name="modifier_id") */
protected $Modifier;
}
和以下控制器代码:
$Employee = new \Base\User();
$Employee->username = "Employee";
$Employee->password = "Just an encrypted password";
$Employee->firstname = "Just";
$Employee->insertion = "a";
$Employee->lastname = "Employee";
$UserStatus = \Base\UserStatus::getById(1);
$Employee->Status = $UserStatus;
$UserStatus->Users->add($Employee);
$em = \Doctrine\Configure\EntityManager::instance();
$em->persist($UserStatus);
$em->persist($Employee);
$em->flush();
控制器代码给我:
PDOException [ 23000 ]: SQLSTATE[23000]: Integrity constraint violation: 1062
Duplicate entry 'To be authenticated' for key 'name'
毋庸置疑,但是在装载UserStatus的名称是“被认证”。不知何故,它试图将UserStatus插入到数据库中,而不是坚持UserStatus的OneToMany关系。
有人能告诉我这段代码有什么问题吗?
@beberlei:当我删除了这一行,我得到一个不同的错误:
InvalidArgumentException [ 0 ]: A new entity was found through a relationship that was
not configured to cascade persist operations: Base\[email protected] Explicitly persist the new entity or
configure cascading persist operations on the relationship.
Tnx分享。恕我直言,单身人士总是有风险的野兽(http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/)。而依赖注入可以帮助解决类似的情况,而不会引入单例造成的问题。只有2cc。 – maraspin 2012-08-11 14:17:59