Symfony2多对一关系

Symfony2多对一关系,symfony,relation,Symfony,Relation,大家好,我的社区 我有个问题,希望你能帮助我。我是Symfony2的新手,尝试建立多对一的关系。但它不起作用 首先,我的两个mySQL表: 表用户 桌辊 映射:User.orm.xml Rolle实体:Rolle.php 实际上-我希望用户表中第一行的值,如username、password、email、isActive、salt、userAccountCreated、userLogDate和rolle表中的角色值作为输出。但正如您所看到的,我得到的不是第二个表中的角色值,而是溢出。你有什么建

大家好,我的社区

我有个问题,希望你能帮助我。我是Symfony2的新手,尝试建立多对一的关系。但它不起作用

首先,我的两个mySQL表:

表用户 桌辊 映射:User.orm.xml Rolle实体:Rolle.php

实际上-我希望用户表中第一行的值,如username、password、email、isActive、salt、userAccountCreated、userLogDate和rolle表中的角色值作为输出。但正如您所看到的,我得到的不是第二个表中的角色值,而是溢出。你有什么建议吗


提前感谢。

您可以通过以下方式获得用户角色:

 ...
 $query = $this->getEntityManager()
        ->createQuery(
            'SELECT u, r FROM User u
            JOIN user.role r
            WHERE u.id = :id'
        )->setParameter('id', $id);

    try {
        return $query->getSingleResult();
    } catch (\Doctrine\ORM\NoResultException $e) {
        return null;
    }
    ...
在上述示例中,进行了两次查询—一次查询原始对象(例如用户),另一次查询相关对象(例如角色对象)。可以通过在原始查询中发出联接来避免第二个查询:


这是一个用户实体对象,尝试调用其getter以获取值,如
$entity->getUsername()
etc请提供一个代码示例。
CREATE TABLE IF NOT EXISTS `rolle` (
`id` int(10) NOT NULL,
  `name` varchar(40) NOT NULL,
  `role` varchar(40) NOT NULL
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;

ALTER TABLE `rolle`
 ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `id` (`id`);

ALTER TABLE `rolle`
MODIFY `id` int(10) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=4;
<?xml version="1.0" encoding="utf-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
  <entity name="dummy\DashboardBundle\Entity\User" table="user" repository-class="dummy\DashboardBundle\Entity\UserRepository">
    <indexes>
      <index name="role_id" columns="role_id"/>
    </indexes>
    <unique-constraints>
      <unique-constraint name="username" columns="username"/>
      <unique-constraint name="email" columns="email"/>
    </unique-constraints>
    <id name="id" type="integer" column="id">
      <generator strategy="IDENTITY"/>
    </id>
    <field name="username" type="string" column="username" length="40" nullable="false"/>
    <field name="password" type="string" column="password" length="127" nullable="false"/>
    <field name="email" type="string" column="email" length="128" nullable="false"/>
    <field name="isActive" type="boolean" column="is_active" nullable="false"/>
    <field name="salt" type="string" column="salt" length="40" nullable="false"/>
    <field name="userAccountCreated" type="datetime" column="user_account_created" nullable="false"/>
    <field name="userLogDate" type="datetime" column="user_log_date" nullable="false"/>
    <many-to-one field="role" target-entity="Rolle">
      <join-columns>
        <join-column name="role_id" referenced-column-name="id"/>
      </join-columns>
    </many-to-one>
  </entity>
</doctrine-mapping> 
<?xml version="1.0" encoding="utf-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
  <entity name="dummy\DashboardBundle\Entity\Rolle" table="rolle">
    <unique-constraints>
      <unique-constraint name="id" columns="id"/>
    </unique-constraints>
    <id name="id" type="integer" column="id">
      <generator strategy="IDENTITY"/>
    </id>
    <field name="name" type="string" column="name" length="40" nullable="false"/>
    <field name="role" type="string" column="role" length="40" nullable="false"/>
  </entity>
</doctrine-mapping>
namespace dummy\DashboardBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * User
 */
class User implements AdvancedUserInterface, \Serializable {

    /**
     * @var string
     */
    private $username;

    /**
     * @var string
     */
    private $password;

    /**
     * @var string
     */
    private $email;

    /**
     * @var boolean
     */
    private $isActive;

    /**
     * @var string
     */
    private $salt;

    /**
     * @var \DateTime
     */
    private $userAccountCreated;

    /**
     * @var \DateTime
     */
    private $userLogDate;

    /**
     * @var integer
     */
    private $id;

    /**
     * @ManyToOne(targetEntity="Rolle")
     * @JoinColumn(name="role_id", referencedColumnName="id")
     **/

    private $role;

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

    /**
     * Set username
     *
     * @param string $username
     * @return User
     */
    public function setUsername($username) {
        $this->username = $username;

        return $this;
    }

    /**
     * Get username
     *
     * @return string 
     */
    public function getUsername() {
        return $this->username;
    }

    /**
     * Set password
     *
     * @param string $password
     * @return User
     */
    public function setPassword($password) {
        $this->password = $password;

        return $this;
    }

    /**
     * Get password
     *
     * @return string 
     */
    public function getPassword() {
        return $this->password;
    }

    /**
     * Set email
     *
     * @param string $email
     * @return User
     */
    public function setEmail($email) {
        $this->email = $email;

        return $this;
    }

    /**
     * Get email
     *
     * @return string 
     */
    public function getEmail() {
        return $this->email;
    }

    /**
     * Set isActive
     *
     * @param boolean $isActive
     * @return User
     */
    public function setIsActive($isActive) {
        $this->isActive = $isActive;

        return $this;
    }

    /**
     * Get isActive
     *
     * @return boolean 
     */
    public function getIsActive() {
        return $this->isActive;
    }

    /**
     * Set salt
     *
     * @param string $salt
     * @return User
     */
    public function setSalt($salt) {
        $this->salt = $salt;

        return $this;
    }

    /**
     * Set role
     *
     * @param \dummy\DashboardBundle\Entity\Rolle $role
     * @return User
     */
    public function setRole(\dummy\DashboardBundle\Entity\Rolle $role = null) {
        $this->role = $role;

        return $this;
    }

    /**
     * Get role
     *
     * @return \dummy\DashboardBundle\Entity\Rolle 
     */
    public function getRole() {
        return $this->role;
    }

    /**
     * Get salt
     *
     * @return string 
     */
    public function getSalt() {
        return null;
    }

    /**
     * Set userAccountCreated
     *
     * @param \DateTime $userAccountCreated
     * @return User
     */
    public function setUserAccountCreated($userAccountCreated) {
        $this->userAccountCreated = $userAccountCreated;

        return $this;
    }

    /**
     * Get userAccountCreated
     *
     * @return \DateTime 
     */
    public function getUserAccountCreated() {
        return $this->userAccountCreated;
    }

    /**
     * Set userLogDate
     *
     * @param \DateTime $userLogDate
     * @return User
     */
    public function setUserLogDate($userLogDate) {
        $this->userLogDate = $userLogDate;

        return $this;
    }

    /**
     * Get userLogDate
     *
     * @return \DateTime 
     */
    public function getUserLogDate() {
        return $this->userLogDate;
    }

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

    // UserInterface

    public function getRoles() {
        return array('ROLE_ADMIN');
    }

    public function eraseCredentials() {

    }

    // AdvancedUserInterface

    public function isAccountNonExpired() {
        return true;
    }

    public function isAccountNonLocked() {
        return true;
    }

    public function isCredentialsNonExpired() {
        return true;
    }

    public function isEnabled() {
        return $this->isActive;
    }

    // serialize and unserialize must be updated - see below
    public function serialize() {
        return serialize(array(
            $this->id,
            $this->username,
            $this->password,
            $this->isActive
        ));
    }

    public function unserialize($serialized) {
        list (
                $this->id,
                $this->username,
                $this->password,
                $this->isActive
                ) = unserialize($serialized);
    }

}
<?php

namespace dummy\DashboardBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Roles
 */
class Rolle {

    /**
     * @var string
     */
    private $name;

    /**
     * @var string
     */
    private $role;

    /**
     * @var integer
     */
    private $id;


    /**
     * Set name
     *
     * @param string $name
     * @return Roles
     */
    public function setName($name) {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string 
     */
    public function getName() {
        return $this->name;
    }

    /**
     * Set role
     *
     * @param string $role
     * @return Roles
     */
    public function setRole($role) {
        $this->role = $role;

        return $this;
    }

    /**
     * Get role
     *
     * @return string 
     */
    public function getRole() {
        return $this->role;
    }

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

}
public function testAction()
{
    $em = $this->getDoctrine()->getManager();
    $entity = $em->getRepository('dummyDashboardBundle:User')->findOneBy(array('id'=>'1'));
    echo '<pre>';
    print_r($entity );
    echo '</pre>';
    return new Response('');
}
dummy\DashboardBundle\Entity\User Object
(
    [username:dummy\DashboardBundle\Entity\User:private] => blabla
    [password:dummy\DashboardBundle\Entity\User:private] => $2a$12$8VsqiLcFSiDQx/LBdJrmtuvxUG523WS1
    [email:dummy\DashboardBundle\Entity\User:private] => blabla@web.de
    [isActive:dummy\DashboardBundle\Entity\User:private] => 1
    [salt:dummy\DashboardBundle\Entity\User:private] => 
    [userAccountCreated:dummy\DashboardBundle\Entity\User:private] => DateTime Object
        (
            [date] => 2015-02-17 00:00:00.000000
            [timezone_type] => 3
            [timezone] => Europe/Berlin
        )

    [userLogDate:dummy\DashboardBundle\Entity\User:private] => DateTime Object
        (
            [date] => 2015-02-17 00:00:00.000000
            [timezone_type] => 3
            [timezone] => Europe/Berlin
        )

    [id:dummy\DashboardBundle\Entity\User:private] => 1
    [role:dummy\DashboardBundle\Entity\User:private] => Proxies\__CG__\dummy\DashboardBundle\Entity\Rolle Object
        (
            [__initializer__] => Closure Object
                (
                    [static] => Array
                        (
                            [entityPersister] => Doctrine\ORM\Persisters\BasicEntityPersister Object
                                (
                                    [class:protected] => Doctrine\ORM\Mapping\ClassMetadata Object
                                        (
                                            [name] => dummy\DashboardBundle\Entity\Rolle
                                            [namespace] => dummy\DashboardBundle\Entity
                                            [rootEntityName] => dummy\DashboardBundle\Entity\Rolle
                                            [customGeneratorDefinition] => 
                                            [customRepositoryClassName] => 
                                            [isMappedSuperclass] => 
                                            [parentClasses] => Array
                                                (
                                                )

                                            [subClasses] => Array
                                                (
                                                )

                                            [namedQueries] => Array
                                                (
                                                )

                                            [namedNativeQueries] => Array
                                                (
                                                )

                                            [sqlResultSetMappings] => Array
$entity->getRole();
 ...
 $query = $this->getEntityManager()
        ->createQuery(
            'SELECT u, r FROM User u
            JOIN user.role r
            WHERE u.id = :id'
        )->setParameter('id', $id);

    try {
        return $query->getSingleResult();
    } catch (\Doctrine\ORM\NoResultException $e) {
        return null;
    }
    ...