Hello Stackoverflow社区,
我有一个问题,希望你能帮助我。我是Symfony2的新手,并尝试建立多对一关系。但它没有用。
首先是我的两个mySQL表:
CREATE TABLE IF NOT EXISTS `user` (
`id` int(10) NOT NULL,
`username` varchar(40) NOT NULL,
`password` varchar(127) NOT NULL,
`email` varchar(128) NOT NULL,
`is_active` tinyint(1) NOT NULL,
`salt` varchar(40) NOT NULL,
`user_account_created` datetime NOT NULL,
`user_log_date` datetime NOT NULL,
`role_id` int(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
ALTER TABLE `user`
ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `username` (`username`), ADD UNIQUE KEY `email` (`email`), ADD KEY `role_id` (`role_id`);
ALTER TABLE `user`
MODIFY `id` int(10) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=4;
ALTER TABLE `user`
ADD CONSTRAINT `user_ibfk_1` FOREIGN KEY (`role_id`) REFERENCES `rolle` (`id`);
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
...
实际上 - 我希望用户表中第一行的值如username,password,email,isActive,salt,userAccountCreated,userLogDate和表rolle中的角色值作为输出。但是你可以看到,而不是第二个表中的角色值,我得到溢出。你有什么建议吗?
提前谢谢。
答案 0 :(得分:0)
您可以使用以下方式获取用户角色:
$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;
}
...