与Doctrine 2不违反

时间:2013-09-06 06:35:43

标签: php doctrine-orm

我想使用Doctrine2将数据插入到数据库中 我有两张桌子:

users
 -name
 -password
 -enabled

groupmembers
 -groupname
 -username

我想创建一个新用户,所以我想把数据放在两个表中 我的课程:

class Users
{
/**
 * @var string
 * @Id @Column(name="name", type="string", length=128, nullable=false)
 * @ORM\GeneratedValue(strategy="SEQUENCE")
 * @ORM\SequenceGenerator(sequenceName="users_name_seq", allocationSize=1, initialValue=1)
 */
private $name;

/**
 * @var string
 * @Column(name="password", type="string", length=254, nullable=true)
 */
private $password;

/**
 * @var string
 * @Column(name="enabled", type="string", nullable=false)
 */
private $enabled;

/**
* @OneToOne(targetEntity="GroupMembers", inversedBy="username")
* @JoinColumn(name="name", referencedColumnName="username")
**/
private $group;
}

class GroupMembers
{
/**
 * @Id @Column(type="string")
 */
protected $groupname;

/**
 *@Id @Column(type="string")
 */
protected $username;

/**
 * @OneToOne(targetEntity="Users", mappedBy="group")
 * @JoinColumn(name="username", referencedColumnName="name")
*/
protected $user;
}

我的代码:

<?php
// addUser.php
require_once "bootstrap.php";

$name = $argv[1];
$pass = "plain:".$argv[2];
$enabled = $argv[3];
$groupname = $argv[4];

$user = new Users();
$user->setName($name);
$user->setPassword($pass);
$user->setEnabled($enabled);

$group = new GroupMembers();
$group->setGroupName($groupname);
$group->setUserName($name);

$entityManager->persist($user);
$entityManager->flush();

$entityManager->persist($group);
$entityManager->flush();

echo "Your new User: ".$user->getName()."\n";

我在字段Not null violation上遇到错误name。如您所见,这个字段的类具有OneToOne关联 什么可能是错的?

更新

我将,cascade="persist"添加到OneToOne注释并更改代码:

<?php
// addUser.php
require_once "bootstrap.php";

$name = $argv[1];
$pass = "plain:".$argv[2];
$enabled = $argv[3];
$groupname = $argv[4];

$user = new Users();
$user->setName($name);
$user->setPassword($pass);
$user->setEnabled($enabled);

$group = new GroupMembers();
$group->setGroupName($groupname);
$group->setUserName($name);
$user->setGroup($group);


 $entityManager->persist($user);
 $entityManager->flush();

 echo "Your new User: ".$user->getName()."\n";

但没有帮助。

1 个答案:

答案 0 :(得分:1)

在用户中:

/**
 * @var string
 * @Id @Column(name="name", type="string", length=128, nullable=false)
 * @ORM\GeneratedValue(strategy="SEQUENCE")
 * @ORM\SequenceGenerator(sequenceName="users_name_seq", allocationSize=1, initialValue=1)
 */
private $name;

应该是

/**
 * @var string
 * @Id
 * @Column(name="name", type="string", length=128, nullable=false)
 */
private $name;

说明: 您的列描述将被忽略,因为它不是有效的注释(不在行的开头)。此序列对您的字符串用户名没有意义。