具有默认继承的Doctrine2+Symfony2



我目前正在开发一个模型,它还不能让我完全满意。我得到了一组具有单一继承的对象,它们引用了另一个对象:

class Category
{
    /** @MongoDBId(strategy="auto") */
    protected $id;
    /** @MongoDBInt */
    protected $categoryId;
    /** @MongoDBString */
    protected $title;
}
class ProductTypeOne extends BaseProductType
{
    /** @MongoDBId(strategy="auto") */
    protected $id;
    /** @MongoDbReferenceOne(targetDocument="Category") */
    private $category;     
}

我现在面临的问题是,当我创建一个对象ProductTypeOne时,我实际上知道它将引用哪个类别——这个ProductType总是一样的。

我可以设置一个修复参数,比如category_id = 1-但Sf2&Doctrine2不允许我从实体(Document,因为我使用的是MongoDB)中查询Category对象。

class ProductTypeOne 
{
    private $category_id = 5;
    public method getCategory()
    {   
       /** how to query the CategoryObject with ID=5? */
    }
}

欢迎任何意见,提前感谢!

然后试试这个:

class ProductTypeOne extends BaseProductType
{
    static $DEFAULT_CATEGORY = 5;
    // rest of the code
}

在插入时[在控制器中],您设置类别:

$product = new ProductTypeOne;
// do whatever you need to fill the instance
$product -> setCategory(
    $this -> getDoctrine() -> getRepository('Category') -> findOneById( ProductTypeOne::$DEFAULT_CATEGORY )
);
// persist $product, beer time

另一种方法是编写自定义ProductTypeOneRepository,并在其方法中注入类别。

最新更新