1

我想使用 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";

但无济于事。

4

1 回答 1

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;

说明:您的 Column-Description 被忽略,因为它不是有效的注释(不在行首)。此外,该序列对您的字符串用户名没有意义。

于 2013-09-06T08:38:29.977 回答