【问题标题】:Doctrine Relationship on a namespaced table命名空间表上的教义关系
【发布时间】:2011-12-02 16:46:23
【问题描述】:

我有几个与其他模型有关系的学说模型。让我们称之为ItemsOneItemsTwoItemsThree。每个都有定义到Products 学说类(产品表)的关系,关系定义为:

$this->hasMany(
    'Models_Products as Products',
    array(
     'local'   => 'id',
     'foreign' => 'product_id',
    )
);

那里没有什么不寻常的地方。

我还有另一个存储命名空间数据的表 (prices)。我的意思是,特定表根据预定义的键(即VinylCDDVD)存储数据,因此行将显示如下内容:

media_namespace  entity_id  quantity    unit_price
CD               4          1000        0.99
DVD              4          2500        1.25
CD               7          3750        0.25
Vinyl            15         75          4.25

entity_id 是访问此表的每个模型的 ID。例如CD/entity_id = 4 指的是ItemsOne 模型,DVD/entity_id = 4 指的是ItemsTwo 模型,等等。

我想创建一个关系 - 我不知道这是否可以完成 - 而它将在模型中命名。所以在上面剪断的产品关系中,我需要类似的东西(对于 ItemsOne 模型):

$this->hasMany(
    'Models_Prices as Prices',
    array(
     'local'   => 'id',
     'foreign' => 'entity_id',
    )
);

但是,以上将返回与entity_id 匹配的所有价格ItemsOne 表部分正确。在上面的示例中,如果entity_id = 4,它将返回CD 记录,但也会返回DVD,这不是我需要的。我希望它根据media_namespace 表过滤数据。所以简而言之,我需要的是:

prices.media_namespace = 'CD' AND prices.entity_id = itemsone.id

以上可以反映在 Doctrine 中的hasMany 关系中吗?我已经搜索过,但找不到有用的东西。

任何指针都非常感谢!

【问题讨论】:

    标签: database namespaces doctrine relationships


    【解决方案1】:

    您需要使用 Doctrine 子类。为每个命名空间创建一个子类。这将允许您按类名引用一组特定的数据。

    • 类 Models_Price
      • Models_Price_CD 子类
      • 子类 Models_Price_DVD
      • Models_Price_Vinyl 子类

    在 Price 类中,您需要指定以下内容:

    public function setUp()
    {
        parent::setUp();
    
        $this->setSubclasses(
            array(
                'Price_CD' => array(
                    'media_namespace' => 'CD',
                ),
                'Price_DVD' => array(
                    'media_namespace' => 'DVD',
                ),
                'Price_Vinyl' => array(
                    'media_namespace' => 'Vinyl',
                ),
            )
        );
    }
    

    假设 ItemsOne 使用命名空间 CD,ItemsTwo 使用命名空间 DVD,ItemsThree 使用命名空间 Vinyl。

    对于这种情况,您可以为每个类添加以下关系:

    ItemsOne:

    $this->hasMany(
        'Models_Price_CD as Prices',
        array(
         'local'   => 'id',
         'foreign' => 'entity_id',
        )
    );
    

    项目二:

    $this->hasMany(
        'Models_Price_DVD as Prices',
        array(
         'local'   => 'id',
         'foreign' => 'entity_id',
        )
    );
    

    项目三:

    $this->hasMany(
        'Models_Price_Vinyl as Prices',
        array(
         'local'   => 'id',
         'foreign' => 'entity_id',
        )
    );
    

    现在,每个价格关系将只返回您所期望的。看到子类的 Doctrine 将自动命名您在该表上执行的所有查询。

    【讨论】:

      猜你喜欢
      • 2017-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-15
      • 2017-04-12
      • 2016-12-04
      相关资源
      最近更新 更多