【发布时间】:2016-02-24 19:12:07
【问题描述】:
我有一个使用 Zend Framework2 和 Doctrine2 作为 ORM 的应用程序。 我有一个名为 User 的实体:
namespace Adm\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\Table(name="user")
*/
class User{
/**
* @ORM\Id
* @ORM\Column(type="integer");
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\Column(type="string")
*/
protected $name;
/**
* @ORM\Column(type="string")
*/
protected $email;
/**
* @ORM\Column(type="string")
*/
protected $password;
/**
* @ORM\ManyToMany(targetEntity="Module")
* @ORM\JoinTable(
* name="user_module",
* joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="module_id", referencedColumnName="id")}
* )
*/
protected $modules;
public function __construct() {
$this->modules = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* @return the $id
*/
public function getId() {
return $this->id;
}
/**
* @return the $name
*/
public function getName() {
return $this->name;
}
/**
* @return the $email
*/
public function getEmail() {
return $this->email;
}
/**
* @return the $password
*/
public function getPassword() {
return $this->password;
}
/**
* @param field_type $id
*/
public function setId($id) {
$this->id = $id;
}
/**
* @param field_type $name
*/
public function setName($name) {
$this->name = $name;
}
/**
* @param field_type $email
*/
public function setEmail($email) {
$this->email = $email;
}
/**
* @param field_type $password
*/
public function setPassword($password) {
$this->password = $password;
}
/**
* Add module
*
* @param dm\Entity\Module
* @return User
*/
public function addModules(Module $modules = null){
$this->modules[] = $modules;
}
/**
* Get modules
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getModules(){
return $this->modules;
}
}
看到 modules 属性是一个多对多关系,带有一个名为 user_modules 的表。 我也有实体模块:
namespace Adm\Entity;
use Doctrine\ORM\Mapping as ORM;
class Module{
/**
* @ORM\Id
* @ORM\Column(type="integer");
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(type="string")
*/
private $name;
/**
* @ORM\Column(type="integer")
*/
private $status;
/**
* @return the $id
*/
public function getId() {
return $this->id;
}
/**
* @return the $name
*/
public function getName() {
return $this->name;
}
/**
* @return the $status
*/
public function getStatus() {
return $this->status;
}
/**
* @param field_type $id
*/
public function setId($id) {
$this->id = $id;
}
/**
* @param field_type $name
*/
public function setName($name) {
$this->name = $name;
}
/**
* @param field_type $status
*/
public function setStatus($status) {
$this->status = $status;
}
}
我收到一个数组变量,其中包含要插入表格的表单中的 Post。正如预期的那样,每个 post 元素在 Entity 中都有它的属性。总之,我有一个 $module 变量,它是一个包含模块 ID 的数组。我的问题是:如何在 user_module 表中插入这些数据? 我的添加功能是这样的:
public function addUser($newUser){
$user = new User();
$user->setName($newUser['name']);
...
$this->getEm()->persist($user);
$this->getEm()->flush();
}
【问题讨论】:
标签: php orm doctrine-orm zend-framework2