製品とカテゴリの2つのモデルがあります。各製品は、プロパティを持ついくつかのカテゴリの一部にすることができweight
ます。これにより、3つのテーブルが得られます。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;
}
}
問題は、カテゴリを保存しようとすると、nullにできないことを示すエラーメッセージが表示されることです。MySQLログでは、コンストラクタで設定しているにもかかわらず、 Doctrineが両方にproduct_id
行を挿入して0に設定しようとしていることを確認しています。 。product_category
product_id
category_id
ProductCategory
私が間違ったことをしたかもしれない提案はありますか?