Symfony - 如何在抽象映射的超类中进行Doctrine搜索?

问题描述 投票:1回答:1

我正在为塑料模型制造商建立一个在线商店(因此是'模型')。

我有一个Product映射超类,因为我想要所有产品(模型,工具,颜料等有名称,价格和描述):

<?php    
namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\Mapping\MappedSuperclass;
use Gedmo\Mapping\Annotation as Gedmo; // gedmo annotations

/** @MappedSuperclass */
abstract class Product
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     * @ORM\Column(type="string", length=100, nullable=false)
     */
    protected $name;

    /**
     * @var int
     * @ORM\Column(type="decimal", scale=2, nullable=false)
     */
    protected $price;

    /**
     * @var string
     * @ORM\Column(type="text", nullable=true)
     */
    protected $description;

    /**
     * @Gedmo\Timestampable(on="create")
     * @ORM\Column(type="datetime")
     */
    private $createdAt;

    /**
     * @ORM\Column(type="datetime")
     * @Gedmo\Timestampable(on="update")
     */
    private $updatedAt;

    //getters and setters...

}

然后,有一个Model类,塑料模型,这扩展了Product类,但也有一个Category能够搜索汽车,飞机,船舶等:

<?php    
namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="model")
 */
class Model extends Product
{

    /**
     * @var Category
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Category", inversedBy="models")
     * @ORM\JoinColumn(name="category_id", referencedColumnName="id", nullable=true)
     */
    private $category;

    /**
     * @return Category
     */
    public function getCategory()
    {
        return $this->category;
    }

    /**
     * @param Category $category
     */
    public function setCategory($category)
    {
        $this->category = $category;
    }


}

当然会有更多类扩展Product映射的超类。现在我想选择最近添加的10种产品,无论其种类如何(型号,工具,涂料)。

我怎么能告诉Doctrine给我最近10个添加的产品?当然我试过像:$this->getDoctrine()->getManager()->getRepository("AppBundle:Product");

但当然它会抛出一个例外

SQLSTATE [42S02]:找不到基表或视图:1146表'modeller_app.product'不存在

这显然是正确的,因为Product是一个抽象类,而不是一个实体。我怎么解决这个问题?

php symfony doctrine-orm symfony-3.3
1个回答
0
投票

你需要使用class table inheritance

这是一个例子:

/**
 * @ORM\Entity
 * @ORM\Table(name="product")
 * @InheritanceType("JOINED")
 * @DiscriminatorColumn(name="discr", type="string")
 * @DiscriminatorMap({"product" = "Product", "model" = "Model"})
 */
class Product
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var string
     * @ORM\Column(type="string", length=100, nullable=false)
     */
    protected $name;

    ...
}

/**
 * @ORM\Entity
 * @ORM\Table(name="product")
 */
class Model extends Product
{
    // Custom properties

    ...
}

现在,您可以查询Product实体,它将返回继承它的所有实体的结果。

© www.soinside.com 2019 - 2024. All rights reserved.