我想使用 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";
但无济于事。