ZF2 - 教义ORM,简单表加入 [英] ZF2 - Doctrine ORM, Simple Table Join

查看:205
本文介绍了ZF2 - 教义ORM,简单表加入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习如何在ZF2中使用Doctrine ORM,目前我的目标是从一个简单的表格连接中检索数据并显示给屏幕。



我有阅读文件,看起来很简单。



这些是我的表:

  user 
- -----------------------
| user_id |名称|电子邮件|
--------------------------
| 1 |约翰| j@b.com |
--------------------------
| 2 |鲍勃| b@j.com |
--------------------------

user_role_linker
------- -------------------
| user_id | role_id |
--------------------------
| 1 |管理员|
--------------------------
| 2 |员工|
--------------------------

我想要实现的是一个列表,我的看法如下:

  ID名称电子邮件角色动作
-------------------------------------------- ------------
1 John j@b.com管理员编辑
2 Bob b@j.com员工编辑
-------- ------------------------------------------------
分页到这里
----------------

这是我目前拥有的,它似乎工作,但我不知道如何抓住连接的表数据:

 用户实体:: 

<?php
命名空间管理\Entity;
使用Doctrine\ORM\Mapping作为ORM;
使用Doctrine\ORM\Mapping\ManyToMany;
使用Doctrine\ORM\Mapping\JoinTable;
使用Doctrine\ORM\Mapping\JoinColumn;
使用Doctrine\Common\Collections\ArrayCollection;

/ ** @ ORM\Entity * /

class User {
/ **
* @ ORM\Id
* @ ORM\GeneratedValue(strategy =AUTO)
* @ ORM\Column(type =integer,name =user_id)
* /

protected $ user_id;

/ ** @ ORM\Column(type =integer,name =parent_id)* /
protected $ parent_id;

/ ** @ ORM\Column(type =string,name =name)* /
protected $ name;

/ ** @ ORM\Column(type =string,name =email)* /
protected $ email;

// Setters和getters

public function getUserId(){
return $ this-> user_id;
}

public function setName($ name){
$ this-> name = $ name;
}

public function getName(){
return $ this-> name;
}

public function getEmail(){
return $ this-> email;
}

public function setEmail($ email){
$ this-> email = $ email;
}

/ **
* @ManyToMany(targetEntity =UserRoleLinker)
* @JoinTable(
* name =user_role_linker,
* joinColumns = {
* @JoinColumn(
* name =user_id,
* referencedColumnName =id)
*},
* inverseJoinColumns = {
* @JoinColumn(
* name =user_id,
* referencedColumnName =id,
* unique = true)
*})
* /
private $ role_id;

public function __construct()
{
$ this-> role_id = new ArrayCollection();
}

/ ** @return Collection * /
public function getRoleId()
{
return $ this-> role_id;
}

}

用户角色链接器实体::

 <?php 
命名空间管理\Entity;
使用Doctrine\ORM\Mapping作为ORM;

/ ** @ ORM\Entity * /
class UserRoleLinker {
/ **
* @ ORM\Id
* @ ORM\\ \\ GeneratedValue(strategy =AUTO)
* @ ORM\Column(type =integer,name =user_id)
* /
protected $ user_id;

/ ** @ ORM\Column(type =string,name =role_id)* /
protected $ role_id;

/ ** @param User | null * /
public function getRoleId(){
return $ this-> role_id;
}
}

我的管理控制器::

  public function usersAction(){
$ em = $ this-> getServiceLocator() - > get('Doctrine\ORM\\ \\EntityManager');
$ userFunctions = new UserFunction($ em);
$ userArray = $ userFunctions-> getUsers();
$ viewModel = new ViewModel(array('users'=> $ userArray));
return $ viewModel;
}

这将调用我的UserFunctions类::

  public function getUsers()
{
//此函数返回用户
return $ this-> em-> getRepository( 'Administration\Entity\User') - >的findAll();
}

在我看来,我列出了这样的数据:

 <?php 
foreach($ this-> users AS $ user){
?>
< tbody>
< tr class =odd gradeX>
< td width =5%><?php echo $ user-> getUserId(); ?>< / TD>
< td><?php echo $ user-> getName(); ?>< / TD>
< td><?php echo $ user-> getEmail(); ?>< / TD>
< td class =center> ***如何显示角色? ***< / TD>
< td>编辑< / td>
< / tr>
<?php}?>

如何获取角色在视图中显示?

解决方案

您必须在实体定义中定义用户和角色之间的正确关系。
我不知道为什么你在这里使用链接表。您是否希望在用户和角色之间实际拥有多对多的关系(每个用户可以有多个角色?)。
如果不能,您可以轻松地将角色ID移动到用户表中,然后在用户和角色之间定义一个 ManyToOne 关系。



您的用户表格将如下所示:

  ---------- --------------------------------- 
| user_id |名称|电子邮件| role_id |
-------------------------------------------
| 1 |约翰| j@b.com |管理员|
-------------------------------------------
| 2 |鲍勃| b@j.com |员工|
-------------------------------------------

我建议看看 ManyToOne 与用户作为拥有方。您可以在 Doctrine2文档



之后,您可以简单地调用 $ user - > getRole(); 在您的视图中



编辑



使用连接表解决一个问题的答案:



这也在这里的教义文档



你需要三个表;用户表,角色表和用户角色链接器表
用户是一个实体,角色是一个实体,角色链接器表不是您的情况下的实体。您应该删除该实体,链接器表仅用于连接数据库中的用户和角色。



用户表

  --------------------------- 
| id |名称|电子邮件|
---------------------------
| 1 |约翰| j@b.com |
---------------------------
| 2 |鲍勃| b@j.com |
---------------------------

角色表

  ------- ---------- 
| id |
-----------------
|管理员|
-----------------
|员工|
-----------------
|客人|
-----------------
|另一个角色|
-----------------

链接器表

  ----------------- --------- 
| user_id | role_id |
--------------------------
| 1 |管理员|
--------------------------
| 2 |员工|
--------------------------

在您的用户实体中:

  / **一对多的单向,表只能与多个简单的约束和一个唯一约束
* @ ORM\ManyToMany(targetEntity =Administration\Entity\Role)
* @ ORM\JoinTable(name = user_role_linker,
* joinColumns = {@ ORM\JoinColumn(name =user_id,referencedColumnName =id)},
* inverseJoinColumns = {@ ORM\JoinColumn(name =role_id ,referencedColumnName =id,unique = true)}
*)
* /
protected $ roles;

/ **
*获取角色。
*
* @return ArrayCollection
* /
public function getRoles()
{
return $ this-> roles;
}

/ **
*向用户添加角色。
*
* @param角色$角色
*
* @return用户
* /
public function addRole(Role $ role)
{
$ this-> roles [] = $ role;

return $ this;
}

/ **
*从用户中删除角色
*
* @param角色$角色
*
* @return用户
* /
public function removeRole(Role $ role)
{
$ this-> roles-> removeElement($ role);

return $ this;
}

您的角色实体:

  / ** 
*表示角色的示例实体。
*
* @ ORM\Entity
* @ ORM\Table(name =role)
* @property string $ id
* /
class角色
{
/ **
* @var string
* @ ORM\Id
* @ ORM\Column(type =string ,length = 255,unique = true,nullable = false)
* /
protected $ id;

/ **
*获取ID。
*
* @return string
* /
public function getId()
{
return $ this-> id;
}
}

我认为这应该可以帮你解决它



也许您应该将以下内容添加到应用程序模块中:

  public function doctrineValidate(MvcEvent $ event){
$ application = $ event-> getParam('application');
$ serviceManager = $ application-> getServiceManager();
$ entityManager = $ serviceManager-> get('doctrine.entitymanager.orm_default');
$ validator = new SchemaValidator($ entityManager);
$ errors = $ validator-> validateMapping();
if(count($ errors)> 0){
//很多错误!
var_dump($ errors);
}
}

然后在引导中:

  $ eventManager-> attach('dispatch',array($ this,'doctrineValidate')); 

在模块中:
原则将通过检查您的实体定义来帮助您。它可能会提前告知您的实体定义有问题...


I am currently learning how to use Doctrine ORM with ZF2 and currently my goal is to retrieve data from a simple table join and display it to screen.

I have read the documents and it looks pretty simple to do.

These are my tables:

user
------------------------
|user_id | name | email   |
--------------------------
| 1      | John | j@b.com |
--------------------------
| 2      | Bob  | b@j.com |
--------------------------

user_role_linker
--------------------------
|user_id | role_id        |
--------------------------
| 1      | administrator  |
--------------------------
| 2      | staff          |
--------------------------

What I want to achieve is a list to my view as follows:

ID       Name       Email      Role              Actions
--------------------------------------------------------
1        John       j@b.com    Administrator     Edit
2        Bob        b@j.com    Staff             Edit
--------------------------------------------------------
Paging goes here
----------------

This is what I currently have and it seems to work except I am not sure how to grab the joined table data:

User entity::

<?php
    namespace Administration\Entity;
    use Doctrine\ORM\Mapping as ORM;
    use Doctrine\ORM\Mapping\ManyToMany;
    use Doctrine\ORM\Mapping\JoinTable;
    use Doctrine\ORM\Mapping\JoinColumn;
    use Doctrine\Common\Collections\ArrayCollection;

    /** @ORM\Entity */

    class User {
        /**
         * @ORM\Id
         * @ORM\GeneratedValue(strategy="AUTO")
         * @ORM\Column(type="integer",name="user_id")
         */

        protected $user_id;

        /** @ORM\Column(type="integer", name="parent_id") */
        protected $parent_id;

        /** @ORM\Column(type="string", name="name") */
        protected $name;

        /** @ORM\Column(type="string", name="email") */
        protected $email;

        //Setters and getters

        public function getUserId() {
            return $this->user_id;
        }

        public function setName($name) {
            $this->name = $name;
        }

        public function getName() {
            return $this->name;
        }

        public function getEmail() {
            return $this->email;
        }

        public function setEmail($email) {
            $this->email = $email;
        }

        /**
        * @ManyToMany(targetEntity="UserRoleLinker")
        * @JoinTable(
        * name="user_role_linker",
        * joinColumns={
        *   @JoinColumn(
        *     name="user_id",
        *     referencedColumnName="id")
        *  },
        * inverseJoinColumns={
            *   @JoinColumn(
             *     name="user_id",
             *     referencedColumnName="id",
             *     unique=true)
             * })
        */
        private $role_id;

        public function __construct()
        {
            $this->role_id = new ArrayCollection();
        }

        /** @return Collection */
        public function getRoleId()
        {
            return $this->role_id;
        }

    }

User role linker entity::

 <?php
    namespace Administration\Entity;
    use Doctrine\ORM\Mapping as ORM;

/** @ORM\Entity */
class UserRoleLinker {
    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="integer",name="user_id")
     */
    protected $user_id;

    /** @ORM\Column(type="string", name="role_id") */
    protected $role_id;

    /** @param User|null */
    public function getRoleId() {
       return $this->role_id;
    }
}

My Administration controller::

public function usersAction() {
   $em = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
   $userFunctions = new UserFunction($em);
   $userArray = $userFunctions->getUsers();
   $viewModel = new ViewModel(array('users' => $userArray));
   return $viewModel;
}

This calls my UserFunctions class::

public function getUsers()
{
    //This function returns the users
    return $this->em->getRepository('Administration\Entity\User')->findAll();
}

And in my view I list the data like this:

<?php
    foreach ($this->users AS $user) {
?>
<tbody>
<tr class="odd gradeX">
    <td width="5%"><?php  echo $user->getUserId(); ?></td>
    <td><?php echo $user->getName(); ?></td>
    <td><?php echo $user->getEmail(); ?></td>
    <td class="center">*** HOW DO I SHOW THE ROLE ?? ***</td>
    <td>Edit</td>
</tr>
<?php } ?>

How do I grab the role to show in the view?

解决方案

You have to define the correct relationship between user and role in your entity definition. I am not sure why you use a linker table here. Do you want to actually have a many to many relationship between user and roles (every user can have several roles?). If not you can easily move the role id into the user table and then you define a ManyToOne relationship between user and role.

Your user table would then look like this:

-------------------------------------------
|user_id | name | email   | role_id       |
-------------------------------------------
| 1      | John | j@b.com | administrator |
-------------------------------------------
| 2      | Bob  | b@j.com | staff         |
-------------------------------------------

I would suggest to take a look at ManyToOne with user as the owning side. You can check how to properly define your unidirectional many to one relation inside your entity definition here in the Doctrine2 documentation

After that you can simply call $user->getRole(); in your view...

EDIT

Answer to fix a one to many using a join table:

This is also described in the doctrine documentation here...

You need three tables; a user table, a role table and a user-role-linker table The user is an entity, the role is an entity the role-linker table is not an entity in your case. You should drop that entity, the linker table is only used for connecting the user and role in the database.

User table

---------------------------
|id      | name | email   |
---------------------------
| 1      | John | j@b.com |
---------------------------
| 2      | Bob  | b@j.com |
---------------------------

Role table

-----------------
| id            |
-----------------
| administrator |
-----------------
| staff         |
-----------------
| guest         |
-----------------
| another role  |
-----------------

Linker table

--------------------------
|user_id | role_id       |
--------------------------
| 1      | administrator |
--------------------------
| 2      | staff         |
--------------------------

In your user entity:

/** ONE-TO-MANY UNIDIRECTIONAL, WITH JOIN TABLE ONLY WORK WITH MANY-TO-MANY ANNOTATION AND A UNIQUE CONSTRAINT
  * @ORM\ManyToMany(targetEntity="Administration\Entity\Role")
  * @ORM\JoinTable(name="user_role_linker",
  *      joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
  *      inverseJoinColumns={@ORM\JoinColumn(name="role_id", referencedColumnName="id", unique=true)}
  *      )
  */
protected $roles;

/**
 * Get roles.
 *
 * @return ArrayCollection
 */
public function getRoles()
{
    return $this->roles;
}

/**
 * Add a role to the user.
 *
 * @param Role $role
 *
 * @return User
 */
public function addRole(Role $role)
{
    $this->roles[] = $role;

    return $this;
}

/**
 * Remove a role from the user
 *
 * @param Role $role
 *
 * @return User
 */
public function removeRole(Role $role)
{
    $this->roles->removeElement($role);

    return $this;
}

Your role entity:

/**
 * An example entity that represents a role.
 *
 * @ORM\Entity
 * @ORM\Table(name="role")
 * @property string $id
 */
class Role
{
    /**
     * @var string
     * @ORM\Id
     * @ORM\Column(type="string", length=255, unique=true, nullable=false)
     */
    protected $id;

    /**
     * Get the id.
     *
     * @return string
     */
    public function getId()
    {
        return $this->id;
    }
}

I think this should help you solve it...

Maybe you should add the following to your application module:

public function doctrineValidate(MvcEvent $event){
    $application = $event->getParam('application');
    $serviceManager = $application->getServiceManager();
    $entityManager = $serviceManager->get('doctrine.entitymanager.orm_default');
    $validator = new SchemaValidator($entityManager);
    $errors = $validator->validateMapping();
    if (count($errors) > 0) {
        // Lots of errors!
        var_dump($errors);
    }
}

And then in bootstrap:

$eventManager->attach('dispatch', array($this, 'doctrineValidate'));

in module: Doctrine will help you by checking your entity definitions. It might tell you in advance that something is wrong in your entity definitions...

这篇关于ZF2 - 教义ORM,简单表加入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆