代码之家  ›  专栏  ›  技术社区  ›  NewRehtse

学说继承

  •  0
  • NewRehtse  · 技术社区  · 7 年前

    我试图在php类中建立一些可能的模型,但我不知道如何在理论中建立关联,也许这是不可能的,也是疯狂的。。。

    我有两个从同一个类继承的类,一个主类可以包含这两个类,所以它包含主类。在这一部分中,我可以轻松添加不同类型的组件。

    public class Main {
        /** @var GlobalClass */
        private $components;
    }
    abstract public GlobalClass {
        /* ... Some code here ... */
    }
    public Class1 extends GlobalClass {
        /* ... Some code here ... */
    }
    public Class2 extends GlobalClass {
        /* ... Some code here ... */
    }
    

    Class1和Class2共享几个属性,但不是所有属性,所以我认为它们是教义的两个不同实体,所以我将GlobalClass映射为mappedSuperclass

    App\Domain\Model\GlobalClass:
        type: mappedSuperclass
        table: global
        id:
                id:
                    type: string
                    generator:
                    strategy: UUID
        fields:
                name:
                    type: string
                    length: 100
    

    还有另外两类:

    App\Domain\Model\Class1:
        type: entity
        table: class1
        repositoryClass: Infrastructure\Persistence\Doctrine\Class1Repo
        fields:
                url:
                        type: string
                        nullable: true
    
    manyToOne:
        main:
            targetEntity: App\Domain\Model\Main
            inversedBy: component
            joinColumn:
                nullable: true
    

    但是在主类的映射中写什么呢?这是我的问题。

    没有manytone关系,一切都正常工作并正确生成模式。但现在,我如何告诉条令$组件可以来自class1表add class2

    这可能是不可能的,我正在以其他方式绕过这个问题,但。。。我想知道是否有人处理过这件事。

    提前非常感谢!

    P、 我想这在Mongo中会更容易,但我需要Doctrien ORM和MySQL。

    2 回复  |  直到 7 年前
        1
  •  1
  •   M. Kebza    7 年前

    在这种情况下,您应该使用类表继承或单表继承来代替映射的超类(取决于哪个更适合您的模式/期望- https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/inheritance-mapping.html#class-table-inheritance )。

    然后,您实际执行了从Main到GlobalClass的许多操作,doctrine将返回集合,其中包含Class1和Class2(取决于保存的内容)。

        2
  •  0
  •   NewRehtse    7 年前

    好的,我昨天晚上一直在想,我想我应该在发布这篇文章之前休息一下,好好想想。。。

    但目前我已经拥有了一些东西,但我不知道为什么我没有这么做。。。很抱歉我写答案是为了有人能用。

    App\Domain\Model\Main:
    type: entity
    table: main
    repositoryClass: Infrastructure\Persistence\Doctrine\MainRepo
    id:
        id:
            type: string
            generator:
            strategy: UUID
    fields:
        status:
            type: integer
    
    oneToMany:
        components:
            targetEntity: App\Domain\Model\GlobalClass
            mappedBy: global
    

    无论如何,如果这不是一个好办法,我想知道:D谢谢。