主义2 ORM Zend 2形式多对多的例子 [英] Doctrine 2 ORM Zend 2 Form Many to Many Example

查看:120
本文介绍了主义2 ORM Zend 2形式多对多的例子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用ZF2和Doctrine 2,任何人都有很多很好的例子,特别是在使用ObjectMultiCheckBox的时候,
我发现这个教程 - https://github.com/ doctrine / DoctrineModule / blob / master / docs / hydrator.md ,但它并没有解释如何做多对多关系。

解决方案

K所以我想出了如何最终在实现hydrator没有约束力协会后,我不得不创建的链接。我要把一个完整的博客帖子解释一下,但是如果你仍然坚持下去。如果你想一起看所有的代码,我已经在 github(链接)介意你正在积极地学习/开发/清理它,所以它有点麻烦



基本上你需要收集所选择的模型,通过将关联链接添加到实体中创建关联链接,然后在Doctrine上使用级联添加/删除活动来持久实体(或者通过在实体之前持久链接来手动执行)。



以下示例是我的帖子和类别之间的多对多



您需要在您的实体上级联活动的属性

  / ** 
* @ ORM\OneToMany(targetEntity =CategoryPostAssociation,mappedBy =category,cascade = {persist,remove})
* /
protected $ category_post_associations;

您需要将对象管理器从窗体推送到您的字段集



PostFieldSet

  $ categoryFieldset = new CategoryFieldset($ objectManager); 
$ this-> add(array(
'type'=>'DoctrineModule\Form\Element\ObjectMultiCheckbox',
'name'=>'categories'
'options'=>数组(
'label'=>'选择类别',
'object_manager'=> $ objectManager,
'should_create_template'=> true,
'target_class'=>'OmniBlog\Entity\Category',
'property'=>'title',
'target_element'=> $ categoryFieldset,
),
));

和categoryfieldset只有一个标题的文本框。



在我的 PostController 的AddAction

  public function addAction(){
//获取您的ObjectManager
$ objectManager = $ this-> getEntityManager();

//创建表单并注入ObjectManager
//将实体绑定到
$ form = new PostForm($ objectManager);
$ post = new Post();
$ form-> bind($ post);

$ request = $ this-> getRequest();
if($ request-> isPost()){
$ form-> setData($ request-> getPost());

if($ form-> isValid()){
/ *
*从表单元素获取ID
*从ID
获取类别*将实体添加到$ post的类别列表
* /
$ element = $ form-> getBaseFieldset() - > get('categories'); // Object of:DoctrineModule\\Form\\Element\\ObjectMultiCheckbox
$ values = $ element-> getValue();

foreach($ values as $ catID){
$ results = $ objectManager-> getRepository('OmniBlog\Entity\Category') - > findBy(array('id '=> $ catID));
$ catEntity = array_pop($ results);
$ link = $ post-> addCategory($ catEntity);
//实体/帖子的关联表级联仍然存在并删除,因此不需要坚持($ link),但将在此完成
}

$ objectManager- >坚持($交);
$ objectManager-> flush();

return $ this-> redirect() - > toRoute(
static :: ROUTE_CHILD,
array('controller'=> static :: CONTROLLER_NAME
));
}
}
返回数组('form'=> $ form);
}

以上如果您看到$ post-> addCategory($ catEntity);这导致我的实体或模型管理链接(我正在传回链接包,我想手动处理级联)



发布 / p>

  / ** 
*返回创建的$ link
* /
public function addCategory类别$ category){
$ link = new CategoryPostAssociation();
$ link-> setCategory($ category);
$ link-> setPost($ this);
$ this-> addCategoryPostAssociations($ link);
return $ link;
}


Anyone have a good and complete example for many to many relation using ZF2 and Doctrine 2, especially when using ObjectMultiCheckBox ? I found this tutorial - https://github.com/doctrine/DoctrineModule/blob/master/docs/hydrator.md but it don't explain how to do a many to many relation.

解决方案

K so I figured out how todo this eventually after realizing the hydrator wasn't binding associations and I had to create the link. I'm going to put a full blog post up explaining it but in case you're still stuck. If you want to look at all the code together I've got it up on github (link) mind you I'm actively learning/developing/cleaning it up so its a bit messy

Basically you need to collect the selected models, create the association link by adding them to the entity, then persist the entity WITH the cascade add/del active on Doctrine (or manually do it by persisting the link's before the entity).

Below example is a Many-to-Many between my Posts and Categories

You need to have cascade active on your entity's property

/**
 * @ORM\OneToMany(targetEntity="CategoryPostAssociation", mappedBy="category",  cascade={"persist", "remove"})
 */
protected $category_post_associations;

You need to push the object manager from your Form to your fieldsets

PostFieldSet

$categoryFieldset = new CategoryFieldset($objectManager);
    $this->add(array(
        'type'    => 'DoctrineModule\Form\Element\ObjectMultiCheckbox',
        'name' => 'categories',
        'options' => array(
            'label' => 'Select Categories',
            'object_manager' => $objectManager,
            'should_create_template' => true,
            'target_class'   => 'OmniBlog\Entity\Category',
            'property'       => 'title',
            'target_element' => $categoryFieldset,
          ),
    ));

and categoryfieldset just has a textbox of the Title.

In my PostController's AddAction

public function addAction() {
    // Get your ObjectManager
    $objectManager = $this->getEntityManager();

    //Create the form and inject the ObjectManager
    //Bind the entity to the form
    $form = new PostForm($objectManager);
    $post = new Post();
    $form->bind($post);

    $request = $this->getRequest();
    if ($request->isPost()) {
        $form->setData($request->getPost());

        if ($form->isValid()) {
            /*
            * Get IDs from form element
            * Get categories from the IDs
            * add entities to $post's categories list
            */
            $element = $form->getBaseFieldset()->get('categories'); //Object of: DoctrineModule\\Form\\Element\\ObjectMultiCheckbox
            $values = $element->getValue();

            foreach($values as $catID){
                $results = $objectManager->getRepository('OmniBlog\Entity\Category')->findBy(array('id' => $catID));
                $catEntity = array_pop($results);                   
                $link = $post->addCategory($catEntity);
                //Entity/Post 's association table cascades persists and removes so don't need to persist($link), but would be done here
            }

            $objectManager->persist($post);
            $objectManager->flush();

            return $this->redirect()->toRoute(
                static::ROUTE_CHILD,
                array('controller' => static::CONTROLLER_NAME
            ));
        }
    }
    return array('form' => $form);
}

Above if you see $post->addCategory($catEntity); this leads to my Entity or Model managing the linking (I was passing back the link encase I want to handle the cascading manually)

Post

    /**
 * Returns the created $link
 */
public function addCategory(Category $category){
    $link = new CategoryPostAssociation();
    $link->setCategory($category);
    $link->setPost($this);
    $this->addCategoryPostAssociations($link);
    return $link;
}

这篇关于主义2 ORM Zend 2形式多对多的例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆