User
和Company
实体之间存在一对一的关系。
在初始化(创建)用户的公司时,用户 ID 应该作为外键绑定到公司用户字段。但不是那样,我收到此错误消息:
属性“id”在“Website\CompanyBundle\Entity\User”类中不公开。也许您应该创建方法“setId()”?
当这个表单是关于公司实体时,为什么 Symfony 想要创建新用户,而用户实体只是一个应该提供用户 ID 的集合。
这是我的代码:
Company.php 实体:
namespace Website\CompanyBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* @ORM\Entity(repositoryClass="Website\CompanyBundle\Entity\Repository\CompanyRepository")
* @ORM\Table(name="company")
*/
class Company
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\OneToOne(targetEntity="User", inversedBy="company")
* @ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
protected $user;
/**
* @ORM\Column(type="string")
*/
protected $name;
}
公司类型.php
class CompanyType extends AbstractType
{
private $security;
public function __construct(SecurityContext $security)
{
$this->security= $security;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$user = $this->securityContext->getToken()->getUser();
$builder
->add('user', new UserType($security))
->add('company_name')
->add('company_address')
...
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Website\CompanyBundle\Entity\Company'
));
}
public function getName()
{
return 'user';
}
}
用户关系类型.php
class UserRelationType extends AbstractType
{
private $user;
public function __construct(SecurityContext $security){
$this->user = $security->getToken()->getUser();
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('id', 'hidden', array('data' => $this->user->getId()))
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Website\CompanyBundle\Entity\User'
));
}
public function getName()
{
return 'user';
}
}
User.php 实体
namespace Website\CompanyBundle\Entity;
use FOS\UserBundle\Entity\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\Table(name="fos_user")
*/
class User extends BaseUser
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\Column(type="string")
*/
protected $name;
/**
* @ORM\OneToOne(targetEntity="Company", mappedBy="user")
*/
protected $company;
}