在Zend_Db_Table_Row中使用关系进行设置

时间:2009-02-03 15:30:24

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

有没有办法如何使用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 个答案:

答案 0 :(得分:3)

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

外键(示例中为$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()将失败。

由于您需要在任何情况下填充主键字段,因此在致电{{1}}时访问该字段并不困难。

答案 1 :(得分:1)

我总是覆盖Zend_Db_Table和Zend_Db_Table_Row并使用我自己的子类。在我的Db_Table课程中,我有:

protected $_rowClass = 'Db_Table_Row';

在我的Db_Table_Row中,我有以下__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;
}