我有两个模型,产品和类别。每个产品都可以是具有weight
属性的多个类别的一部分。这给出了三个表;product
,category
和product_category
. 这是我的模型:
/** @Entity @Table(name="product") **/
class Product
{
/** @Id @Column(type="integer") @GeneratedValue **/
protected $id = null;
/** @OneToMany(targetEntity="ProductCategory", mappedBy="product", orphanRemoval=true, cascade={"persist","remove"}) @var ProductCategory[] **/
protected $productCategories = null;
public function __construct ()
{
$this->productCategories = new ArrayCollection();
}
// Take an array of category_ids of which the product should be part of. The first category gets weight=1, next weight=2 etc.
public function saveCategories ($category_ids)
{
$weight = 1;
$this->productCategories = new ArrayCollection();
foreach ($category_ids as $category_id)
$this->productCategories[] = new ProductCategory($this->id, $category_id, $weight++);
}
}
/** @Entity @Table(name="category") **/
class Category
{
/** @Id @Column(type="integer") @GeneratedValue **/
protected $id = null;
/** @Column(type="string",length=200,nullable=false) @var string **/
protected $title = null;
/** @OneToMany(targetEntity="ProductCategory", mappedBy="category") @var ProductCategory[] **/
protected $productCategories = null;
public function __construct()
{
$this->productCategories = new ArrayCollection();
}
}
/** @Entity @Table(name="product_category") **/
class ProductCategory
{
/** @Id @Column(type="integer",nullable=false) **/
protected $product_id = null;
/** @Id @Column(type="integer",nullable=false) **/
protected $attraction_id = null;
/** @Column(type="integer",nullable=false) **/
protected $weight = null;
/** @ManyToOne(targetEntity="Product",inversedBy="productCategories") @JoinColumn(name="product_id",referencedColumnName="id",onDelete="CASCADE") @var Product **/
protected $product;
/** @ManyToOne(targetEntity="Category",inversedBy="productCategories") @JoinColumn(name="category_id",referencedColumnName="id",onDelete="CASCADE") @var Category **/
protected $category;
public function __construct ($product_id, $category_id, $weight)
{
$this->product_id = $product_id;
$this->attraction_id = $attraction_id;
$this->weight = $weight;
}
}
问题是,当我尝试保存类别时,我收到一条错误消息,指出product_id
不能为空 - MySQL 日志确认 Doctrine 尝试将一行插入product_category
两者product_id
并category_id
设置为 0,尽管我在ProductCategory
构造函数中设置了它们.
有什么建议我可能做错了吗?