【问题标题】:How to extend entity with internal relation?如何扩展具有内部关系的实体?
【发布时间】:2019-04-23 08:53:55
【问题描述】:

我希望您能提供帮助,因为我已经搜索了几天。 我有一个名为“属性”的类。其中有一个parentId,它引用了另一个Attributes 条目。

我想用一些额外的字段将实体“属性”扩展为“产品”。除了parentId 关系之外,所有字段都在扩展。

当我使用 getter 和 setter 将父级添加到 Products 时,出现错误:

`"Compile Error: Declaration of Products::setParent(?Attributes $parent): Products must be compatible with Attributes::setParent(?Attributes $parent)
  : Attributes"`

我已经尝试了一个独立的实体Products,其中包含所有字段,但与Attributes 的关系会导致数据库关系问题。它是Attributes 的扩展。

尝试了不同类型的 getter 和 setter,并将其从父级扩展。

一直在网上搜索答案,但没有看到具有内部关系的继承。

属性类:

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity()
 */
class Attributes
{
    /**
     * @ORM\Id()
     * @ORM\Column(type="string", length=255)
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $val;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $category;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Attributes")
     * @ORM\JoinColumn(name="parent_id", referencedColumnName="id")
     */
    private $parent;
}

产品类:

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity()
 */
class Products extends Attributes
{
   /**
     * @ORM\Column(type="string", length=255)
     */
    private $newField1;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $newField2;
}

我想知道为什么内部关系“Parent”没有被扩展,我很想知道如何在扩展类中获取 parentId。

【问题讨论】:

  • 查看下面的链接以获取类似的示例。 Similar Example Here
  • @DavidKariuki 确实很有趣,但我没有使用抽象类来扩展,因为属性也是可以调用的类。

标签: php doctrine symfony4


【解决方案1】:

你的父 setter 似乎是这样的:

/** Product **/
public function setParent(?Attributes $parent): Products
{
   $this->parent = $parent;

   return $this;
}
/** Attribute **/
public function setParent(?Attributes $parent)
{
   $this->parent = $parent;

   return $this;
}

您只需在产品类的 setParent 行末尾将 :Products 替换为 :Attributes 即可解决此问题。

但你应该使用界面

interface AttributeInterface 
{
    public function setParent(?AttributeInterface $parent): AttributeInterface
}

你的每个实体都应该实现它:

属性:

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity()
 */
class Attributes implements AttributesInterface
{
    /*****/
    public function setParent(?AttributeInterface $parent): AttributeInterface
    {
        $this->parent = $parent;

        return $this;
    }
}

产品:

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity()
 */
class Products extends Attributes implements AttributesInterface
{
   /*****/
}

【讨论】:

  • 我尝试删除 : Products 但它仍然给出了同样的错误。我现在将尝试使用属性接口来制作它。
  • 我编辑了我的答案,请将 :Products 替换为 :Attributes (但这仍然是使用属性接口的最佳方式。)
  • 我尝试使用 Attributes 并且我刚刚创建了一个界面,但是 parentId 和其他关系没有显示在数据库中。
猜你喜欢
  • 1970-01-01
  • 2014-06-16
  • 1970-01-01
  • 2021-08-03
  • 2021-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多