代码之家  ›  专栏  ›  技术社区  ›  Martin Rázus

使用关系在Zend_Db_Table_行中进行设置

  •  1
  • Martin Rázus  · 技术社区  · 16 年前

    有没有办法使用Zend_Db关系设置相关对象? 我正在寻找以下代码:

    $contentModel = new Content();          
    $categoryModel = new Category();
    
    $category = $categoryModel->createRow();
    $category->setName('Name Category 4');
    
    $content = $contentModel->createRow();
    $content->setTitle('Title 4');
    
    $content->setCategory($category);
    $content->save();
    

    这提供了小型图书馆: http://code.google.com/p/zend-framework-orm/

    有人有这方面的经验吗?ZF没有类似的计划吗?还是有更好的使用方法?(我不想使用ORM或外部的东西)

    谢谢

    2 回复  |  直到 16 年前
        1
  •  3
  •   Bill Karwin    15 年前

    我在Zend框架中设计并实现了表关系代码。

    外键( $content->category 在您的示例中)包含它引用的父行中主键的值。在你的例子中 $category 尚未包含主键值,因为您尚未保存它(假设它使用自动递增的伪密钥)。你救不了我 $content 行,直到填充其外键,以便满足引用完整性:

    $contentModel = new Content();                  
    $categoryModel = new Category();
    
    $category = $categoryModel->createRow();
    $category->setName('Name Category 4');
    
    $content = $contentModel->createRow();
    $content->setTitle('Title 4');
    
    // saving populates the primary key field in the Row object
    $category->save();
    
    $content->setCategory($category->category_id);
    $content->save();
    

    将Row对象传递给 setCategory() 如果没有填充主键。 $content->save() 如果没有有效的主键值可供引用,则将失败。

    由于在任何情况下都需要填充主键字段,因此在调用时访问该字段并不困难 setCategory() .

        2
  •  1
  •   smack0007    16 年前

    我总是重写Zend_Db_Table和Zend_Db_Table_行,并使用自己的子类。在我的Db_Table课程中,我有:

    protected $_rowClass = 'Db_Table_Row';
    

    在我的Db_Table_行中,我有以下_get()和_set()函数:

    public function __get($key)
    {
        $inflector = new Zend_Filter_Word_UnderscoreToCamelCase();
    
        $method = 'get' . $inflector->filter($key);
    
        if(method_exists($this, $method)) {
            return $this->{$method}();
        }
    
        return parent::__get($key);
    }
    
    public function __set($key, $value)
    {
        $inflector = new Zend_Filter_Word_UnderscoreToCamelCase();
    
        $method = 'set' . $inflector->filter($key);
    
        if(method_exists($this, $method))
            return $this->{$method}($value);
    
        return parent::__set($key, $value);
    }
    

    基本上,这只是告诉类寻找名为getFoo()和setFoo()的方法。然后,只要你在后面写下自己的逻辑,你几乎可以组成自己的领域。在你的情况下,也许:

    public function setCategory($value)
    {
         $this->category_id = $value->category_id;
    }