【问题标题】:Zend_Db relationships from diagramZend_Db 关系图
【发布时间】:2011-06-20 22:35:29
【问题描述】:

我有以下表格:

每个都有自己的映射器:
Product_Model_DbTable_Product
Product_Model_DbTable_Category
Product_Model_DbTable_ProdCategRelation

我已经看到 some tutorials 关于它是如何完成的,但我仍然不明白。


这是我目前拥有的:

class Product_Model_DbTable_Product extends Zend_Db_Table_Abstract
{

    protected $_name = 'product';
    protected $_dependentTables = array('Product_Model_DbTable_ProdCategRelation');
}

class Product_Model_DbTable_Category extends Zend_Db_Table_Abstract
{

    protected $_name = 'category';
    protected $_dependentTables = array('Product_Model_DbTable_ProdCategRelation');
}

class Product_Model_DbTable_ProdCategRelation extends Zend_Db_Table_Abstract
{
    protected $_name = 'product_category';
    protected $_referenceMap = array(
        'Product' => array(
            'columns' => 'pid',
            'refTableClass' => 'Product_Model_DbTable_Product',
            'refColumns' => 'id'
        ),
        'Category' => array(
            'columns' => 'cid',
            'refTableClass' => 'Product_Model_DbTable_Category',
            'refColumns' => 'id'  
        )
    );
}

还有我的实验性控制器代码(或多或少可以工作,但方法似乎不对;还不如回到普通的表连接):

public function indexAction()
{
    $productObj = new Product_Model_DbTable_Product;
    $categoryObj = new Product_Model_DbTable_Category();

    $product = $productObj->fetchRow('id = 1');
    $productRelation = $product->findDependentRowset('Product_Model_DbTable_ProdCategRelation', 'Product')->current();

    $category = $categoryObj->fetchRow('id = ' . $productRelation->cid);
    $categoryInfo = $category->findDependentRowset('Product_Model_DbTable_ProdCategRelation', 'Category')->current();
}

我能否仅通过实例化一个产品而不是全部实例化这些关系来获取产品的类别?

【问题讨论】:

    标签: zend-framework zend-db table-relationships


    【解决方案1】:

    您可以为此目的使用findManyToManyRowset。因此您的代码可能会转换为:

    $product = $productObj->fetchRow('id = 1');
    $categoryInfo = $product->findManyToManyRowset(
        'Product_Model_DbTable_Category',
        'Product_Model_DbTable_ProdCategRelation'
    )->current();
    

    【讨论】:

    • 但如果没有 current(),它将只返回行集中的第一行 - 我认为,如果产品有多个类别,OP 想要全部。
    • 我认为我的 $_dependentTables$_referenceMap 是正确的。
    • @singles current() 仅取自 OP 的原始代码。虽然我同意,但产品 - 类别可能不是 1:1 的关系。
    猜你喜欢
    • 1970-01-01
    • 2011-06-17
    • 2012-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多