我正在使用Symfony 3来建立一个网站。我有一个与Users
关系的实体(OneToOne
),以便结交。 (我没有其他人知道如何轻松地做到这一点)
最终目标是创建一个表格来引用id
中其他Users
的couple
。所以我创建了一个IntegerType
字段并将其分配给id
但我无法设置它(因为没有setId(...)
)。所以我会知道是否有setter
选项(在Doc / Tests中找不到),如果没有,我怎么能实现这个?
注册新夫妇的步骤将是:
Users
)[FORM]Users
($userCouple = ...findOne...
)[BDD]$couple == null
然后$userCouple->setCouple($this)
和$this->setCouple($userCouple)
所以我的Users
实体看起来像:
<?php
namespace Acme\UserBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use FOS\UserBundle\Model\User as BaseUser;
/**
* Users
*
* @ORM\Table(name="users")
* @ORM\Entity(repositoryClass="Acme\UserBundle\Repository\UsersRepository")
*/
class Users extends BaseUser
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\OneToOne(targetEntity="Acme\UserBundle\Entity\Users")
* @ORM\JoinColumn(nullable=true)
*/
protected $couple;
/**
* Get id
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Set couple.
*
* @param \Acme\UserBundle\Entity\Users|null $couple
*
* @return Users
*/
public function setCouple(\Acme\UserBundle\Entity\Users $couple = null)
{
$this->couple = $couple;
return $this;
}
/**
* Get couple.
*
* @return \Acme\UserBundle\Entity\Users|null
*/
public function getCouple()
{
return $this->couple;
}
}
我的表格看起来像:
<?php
namespace Acme\UserBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
class ProfileFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('couple', IntegerType::class, array(
'label' => 'Couple ID',
'property_path' => 'couple.id',
'attr' => array('min' => 0),
));
}
public function getBlockPrefix()
{
return 'acme_user_profile';
}
}
您应该使用一对一的自引用关系来解决这个问题(请参阅更多here)。基本上你的couple
将被partner
取代,它最适合这种情况:
...
/**
* @OneToOne(targetEntity="User")
* @JoinColumn(name="partner_id", referencedColumnName="id")
*/
protected $partner;
...
然后在表单中你可以使用EntityType
(不知道为什么你想首先使用IntegerType
)并做这样的事情:
$builder->add('users', EntityType::class, array(
// query choices from this entity
'class' => 'UserBundle:User',
// use the User.username property as the visible option string
'choice_label' => 'username',
));
当然,您可以使用query_builder
选项(传递自定义查询)或choices
从您显示为可能的合作伙伴的用户列表中排除您正在编辑配置文件的用户,以传递您要使用的用户实体的集合(首先获取它们和过滤掉当前用户)。