【问题标题】:doctrine 2: inheritance mapping join with parent table教义2:继承映射join与父表
【发布时间】:2018-01-16 12:36:21
【问题描述】:

我有一个这样的基表:

class BaseProduct 
{
    /**
     * @ORM\ManyToOne(targetEntity="ProductBundle\Entity\Category", inversedBy="baseProducts")
     * @ORM\JoinColumn(name="menu_category_id", referencedColumnName="id", nullable=true)
     **/
    protected $category;
// ...

以及从 BaseProduct 继承的另一个实体

class ChildProduct extends BaseProduct
{

    /**
     * @ORM\ManyToOne(targetEntity="ProductBundle\Entity\Category", inversedBy="childProducts")
     * @ORM\JoinColumn(name="menu_category_id", referencedColumnName="id", nullable=true)
     **/
    protected $category;

和类别实体:

class Category 
{
    /**
     * @ORM\OneToMany(targetEntity="ProductBundle\Entity\BaseProduct", mappedBy="category")
     * @ORM\OrderBy({"position"= "ASC"})
     */
    private $baseProducts;

    /**
     * @ORM\OneToMany(targetEntity="ProductBundle\Entity\ChildProduct", mappedBy="category")
     * @ORM\OrderBy({"position"= "ASC"})
     */
    private $childProducts;

我的ChildProduct 表有一列名为id 并引用了BaseProduct id。现在我想用这个查询加入类别ChildProduct

    $qb->select('mc', 'cp')
        ->from('ProductBundle:Category', 'mc')
        ->leftJoin('mc.childProducts', 'cp')
        // .....

当我执行这个查询时,它给出了这个错误:

SqlWalker.php 第 922 行中的 ContextErrorException:

注意:未定义索引:childProducts

虽然我在类别中有childProducts

现在我有两个问题:

  1. 我能否查询子表中不存在的父字段。
  2. 我的查询出了什么问题

【问题讨论】:

  • 你试过运行doctrine:schema:validate吗?
  • 是的,我有,但没有帮助
  • $baseProducts OneToMany 注释是否应该引用 BaseProduct 实体?不知道为什么会导致这个错误,但它看起来不正确。
  • 在我的代码中是正确的。这只是发布问题时的一个错字。

标签: php mysql symfony doctrine-orm


【解决方案1】:

查看学说章节继承映射:Inheritance Mapping

按照文档试试这个(我没有测试代码)

/** @ORM\MappedSuperclass */
class BaseProduct 
{
    /**
      * @ORM\ManyToOne(targetEntity="ProductBundle\Entity\Category", inversedBy="baseProducts")
      * @ORM\JoinColumn(name="menu_category_id", referencedColumnName="id", nullable=true)
     **/
     protected $category;

现在 Doctrine 知道你的类是其他类的基类。 你所要做的就是扩展基类并添加注解@ORM\Entity

/**
 * @ORM\Entity()
 **/
class ChildProduct extends BaseProduct
{

    /**
     * @ORM\ManyToOne(targetEntity="ProductBundle\Entity\Category", inversedBy="childProducts")
     * @ORM\JoinColumn(name="menu_category_id", referencedColumnName="id", nullable=true)
    **/
    protected $category;

我认为您可以从 ChildProduct $category 字段中删除。它也应该可以工作。

【讨论】:

    猜你喜欢
    • 2015-06-30
    • 1970-01-01
    • 1970-01-01
    • 2013-06-04
    • 1970-01-01
    • 1970-01-01
    • 2015-12-21
    • 2023-04-08
    • 2015-07-01
    相关资源
    最近更新 更多