家庭实体与成员实体具有 1:n 关系。这些实体在创建新家庭时很容易保留。我不知道如何最好地指定成员集合中的一个也是唯一一个作为户主。该模型显示具有成员 ID 的家庭实体,即负责人,成员实体具有家庭 ID。因此,当创建家庭实体和组成成员实体时,头部的 ID 是未知的。我正在寻找有关如何建立这种户主关系的建议。
根据请求,代码。在其中添加了解决方案代码。信用应该去评论者 nifr !!:
家庭实体片段(hohId 是户主的 id,客户是成员):
/**
* Household
*
* @ORM\Table(name="household")
* @ORM\Entity
*/
class Household
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var integer
*
* @ORM\Column(name="hoh_id", type="integer", nullable=true)
*/
private $hohId;
...
/**
* @var \Doctrine\Common\Collections\Collection
*
* @ORM\OneToMany(targetEntity="Mana\ClientBundle\Entity\Client", mappedBy="household")
* @ORM\OrderBy({"id" = "ASC"})
*/
private $clients;
...
//added for solution:
/**
* @var object Member as head of household
* @ORM\OneToOne(targetEntity="Member")
* @ORM\JoinColumn(name="hoh_id", referencedColumnName="id")
* */
private $head;
public function setHead($member) {
$this->head = $member;
return $this;
}
public function getHead() {
return $this->head;
}
}
客户端(实际上,成员)实体片段:
/**
* Client
*
* @ORM\Table(name="client", indexes={@ORM\Index(name="idx_client_household_idx", columns={"household_id"}), @ORM\Index(name="idx_client_ethnicity_idx", columns={"ethnicity_id"})})
* @ORM\Entity
*/
class Client
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
...
/**
* @var \Mana\ClientBundle\Entity\Household
*
* @ORM\ManyToOne(targetEntity="Mana\ClientBundle\Entity\Household", inversedBy="clients", cascade={"persist"})
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="household_id", referencedColumnName="id")
* })
*/
private $household;
...
}
HouseholdType 表单类片段:
->add('isHead','choice', array(
'expanded' => true,
'mapped' => false,
)
原型表单片段:
<tr id="member-form">
<td><input class="smallform" type="radio" name="household[isHead]" value="__name__"></td>
<td>{{ form_widget(form.fname, {'attr': {'class':'smallform'}}) }}</td>
<td>{{ form_widget(form.sname, {'attr': {'class':'smallform'}}) }}</td>
<td>{{ form_widget(form.dob, {'attr': {'class':'smallform'}}) }}</td>
<td>{{ form_widget(form.sex, {'attr': {'class':'smallform'}}) }}</td>
<td>{{ form_widget(form.ethnicity, {'attr': {'class':'smallform'}}) }}</td>
家庭控制器片段:
public function createAction(Request $request) {
$household = new Household();
$form = $this->createForm(new HouseholdType(), $household);
$form->bind($request);
if ($form->isValid()) {
$members = $household->getMembers();
$em = $this->getDoctrine()->getManager();
//get household head index
$h = $request->request->get('household');
$hohIdx = $h['isHead'];
$i = 1;
foreach ($members as $member) {
if ($i == $hohIdx) {
$household->setHead($member);
}
$i++;
$member->setHousehold($household);
}
$em->persist($household);
$em->flush();
return $this->redirect($this->generateUrl('household_show', array('id' => $household->getId())));
}
//...
}