我试图在 Symfony2 中使用查询构建器在用户和帐户之间建立多对多关系,但我失败了。这是 DQL
return $er->createQueryBuilder('a')
->leftJoin('\FEB\UserBundle\Entity\Userr', 'u')
->where('a.id = :id')
->setParameter('id', $options['pepe']);
这是实体:
用户.php
namespace FEB\UserBundle\Entity;
use FOS\UserBundle\Entity\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\Table(name="feb_user")
*/
class User extends BaseUser
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
public function __construct()
{
parent::__construct();
// tu propia lógica
}
}
账户.php
namespace FEB\UserBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Account
*
* @ORM\Table()
* @ORM\Entity(repositoryClass="FEB\UserBundle\Entity\AccountRepository")
*/
class Account
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* Many-To-Many, Unidirectional
*
* @var ArrayCollection $idusr
*
* @ORM\ManyToMany(targetEntity="\FEB\UserBundle\Entity\User")
* @ORM\JoinTable(name="accounts_users",
* joinColumns={@ORM\JoinColumn(name="account_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="usr_id", referencedColumnName="id")}
* )
*/
private $idusr;
public function __construct() {
$this->idusr = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Set idusr
*
* @param string $idusr
* @return Account
*/
public function setIdusr($idusr)
{
$this->idusr = $idusr;
return $this;
}
/**
* Get idusr
*
* @return integer
*/
public function getIdusr()
{
return $this->idusr;
}
当我执行 DQL 时,我得到了“帐户”表的所有记录,而不是连接:
我要运行的 SQL 语句是这样的:
SELECT *
FROM Account a
LEFT JOIN accounts_users au ON ( au.usr_id = a.id )
WHERE au.usr_id = 1
我该如何解决?
编辑1:
这个想法是检索结果以填充帐户表单中的下拉列表:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('titulo')
->add('tweet', 'textarea')
->add('photo', 'file', array('required' => false))
->add('tags', 'entity', array(
'class' => 'FEBTagsBundle:tag',
'property' => 'tag',
'empty_value' => 'Selecciona tags',
'multiple' => true))
->add('idaccount', 'entity', array(
'class' => 'FEBUserBundle:Account',
'property' => 'username',
'query_builder' => function(EntityRepository $er ) use ($options) {
return $er->createQueryBuilder('a')
->leftJoin('\FEB\UserBundle\Entity\User', 'u')
->where('a.id = :id')
->setParameter('id', $options['pepe']);
//->andWhere('w.visible = 1')
//->andWhere('w.booked = 0');
;},
'empty_value' => 'Selecciona account',
'multiple' => false))
;
}
EDIT2:更多信息。目标是:从“feb_user”表的 id 中,我得到“Account”表的用户名。feb_user 表和 Account 表通过“accounts_users”表相关联。