繁体   English   中英

在原则中处理一对一的单向关系

[英]Working with One-to-One unidirectional relationship in Doctrine

我有一个名为Install的实体,它具有两个属性:主机名和服务呼叫号码。 服务电话号码是可选的。 我创建了另一个名为ServiceCall的实体,该实体与Install实体具有一对一的单向关系,而不是允许该字段为null并违反1NF。 我的问题是,当我在表单中输入主机名和服务调用并提交时,仅主机名被保留,服务调用和关系不被保留。 这是我的代码:

服务呼叫实体

class ServiceCall
{
/**
 * @var integer
 */
private $id;

/**
 * @var integer
 */
private $serviceCall;

private $install;

// Getters / Setters
}

安装实体

class Install
{
/**
 * @var integer
 */
private $id;

/**
 * @var string
 */
private $hostname;

private $serviceCall;

// Getters / Setters
}

关系配置:

AppBundle\Entity\Install:
type: entity
table: null
id:
    id:
        type: integer
        id: true
        generator:
            strategy: AUTO
fields:
    hostname:
        type: string
        length: 255
lifecycleCallbacks: {  }

AppBundle\Entity\ServiceCall:
type: entity
table: null
id:
    id:
        type: integer
        id: true
        generator:
            strategy: AUTO
fields:
    serviceCall:
        type: integer
lifecycleCallbacks: {  }
oneToOne:
    install:
        targetEntity: AppBundle\Entity\Install
        joinColumn:
            name: install_id
            referencedColumnName: id

控制器方式:

public function createAction(Request $request)
{
    $entity = new Install();
    $form = $this->createCreateForm($entity);
    $form->handleRequest($request);

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();

        $em->persist($entity);
        $em->flush();

        return $this->redirect($this->generateUrl('install_show', array('id' => $entity->getId())));
    }

    return $this->render('AppBundle:Install:new.html.twig', array(
        'entity' => $entity,
        'form'   => $form->createView(),
    ));
}

安装表格类型

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('hostname')
        ->add('serviceCall', new ServiceCallType())
    ;
}

服务电话表格类型

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('serviceCall')
    ;
}

您必须为Install条目而不是ServiceCall实体添加OneToOne关系。

并且不要忘记为关系添加级联持久选项。

并且还需要创建新的ServiceCall实体进行关联。

为此,请使用ServiceCallFormType中的DataTransformer

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM