【问题标题】:TYPO3, Extbase: set mm_relationTYPO3,Extbase:设置 mm_relation
【发布时间】:2014-05-08 15:15:40
【问题描述】:

我只是在使用 extbase 进行尝试,但在使用两个表(存储库)和一个 mm_table 来存储关系时遇到了问题。

表格是:

  • 可寻址
  • 分类表
  • address_category mm 表

我创建了一个地址类型的对象,并且可以毫无问题地设置名称等。但也有一个类别表,这两个表通过 mm_table 关联。而这种关系我只能在 TYPO3 后端建立,而不能在插件中建立。

代码是这样的:

// get repo
$addressRepo = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\GoMapsExt\Domain\Repository\AddressRepository');
$addressCategoryRepo = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\GoMapsExt\Domain\Repository\CategoryRepository');

// get category object (lead = 2))
$addressCategoryObj = $addressCategoryRepo->findByUid(2);
// attach category to address
//$go_map_address->setCategories($addressCategoryObj);   <-- need to add category here

如何添加这样的关系?似乎没有 setCategory 方法。

【问题讨论】:

    标签: typo3 extbase


    【解决方案1】:

    首先,检查模型内部的功能。你肯定有 addCategory()、getCategories()、removeCategory() 或 setCategories() 之类的函数。

    其次,如果确实需要,不要使用 makeInstance 函数获取存储库(它已过时),只需注入它或使用 ObjectManager:

    /**
     * categoryRepository
     *
     * @var \TYPO3\GoMapsExt\Domain\Repository\CategoryRepository
     * @inject
     */
    protected $categoryRepository;
    

    或/和

    $objectManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Object\\ObjectManager');
    
    if (!is_object($this->categoryRepository)) {
        $this->categoryRepository = $objectManager->get('TYPO3\\GoMapsExt\\Domain\\Repository\\CategoryRepository');
    }
    

    因为 Typo3 可能有问题,所以我通常同时使用。

    【讨论】:

    • 谢谢。 ect go_maps_ext 中的添加/删除函数出错。它已在本地更改并再次运行:-)
    【解决方案2】:

    在extbase中使用mm等关系非常简单。首先您需要配置与 TCA 的关系,如果它在后端工作,那么您已经完成了这部分。其次,您需要像这样在模型中配置属性:

    /**
     * @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\TYPO3\GoMapsExt\Domain\Model\Category>
     * @lazy
     */
    protected $categories;
    
    
    /**
     * @param \TYPO3\CMS\Extbase\Persistence\ObjectStorage $categories
     */
    public function setCategories($categories) {
        $this->categories = $categories;
    }
    
    /**
     * @return \TYPO3\CMS\Extbase\Persistence\ObjectStorage
     */
    public function getCategories() {
        // this prevents a fatal error if you have created your model with new instead of the objectManager
        if ($this->categories === null) {
            $this->categories = new \TYPO3\CMS\Extbase\Persistence\ObjectStorage();
        }
        return $this->categories;
    }
    

    在Controller中可以添加/删除/遍历类别:

    $go_map_address->getCategories->attach($addressCategoryObj);
    
    foreach ($go_map_address->getCategories() as $category) {
        //$category
    }
    

    请记住,在向存储库添加类别后,您必须将 $go_map_address 与存储库一起保存,就像对对象的所有其他更改一样

    【讨论】:

      猜你喜欢
      • 2017-06-02
      • 2013-06-19
      • 2012-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多