使用 cascade={ "persist" } 保存 Doctrine2 记录时出现问题,在显式指定后尝试插入事件 null PK



>我有两个模型,产品和类别。每个产品都可以属于具有weight属性的多个类别。这给出了三个表;productcategoryproduct_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_idcategory_id都设置为 0 的情况下将一行插入到product_category中,尽管我在ProductCategory构造函数中设置了它们。

有什么建议我可能做错了什么吗?

你做错了。在教义2中,没有所谓的product_id,也没有category_id。您只处理产品和类别实体,列值由原则本身处理。

而不是

....
foreach ($category_ids as $category_id)
$this->productCategories[] = new ProductCategory($this->id, $category_id, $weight++);

你应该有类似的东西

public function saveCategories ($categories)
{
foreach ($categories as $category)
$this->productCategories[] = new ProductCategory($this, $category)

修复 ProductCategory 的构造函数以反映这些内容,并删除category_id和product_id定义。

最新更新