我正在为塑料模型制造商建立一个在线商店(因此是'模型')。
我有一个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
是一个抽象类,而不是一个实体。我怎么解决这个问题?
你需要使用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实体,它将返回继承它的所有实体的结果。