【问题标题】:Handling one-to-many relationship with ZF partialLoop使用 ZF partialLoop 处理一对多关系
【发布时间】:2010-01-20 16:12:48
【问题描述】:

假设我正在列出音乐艺术家,每个艺术家都有存储在艺术家表中的基本信息,如姓名、年龄等。它们在专辑表中也有条目(专辑名称/专辑封面等),使用艺术家 ID 作为外键引用艺术家表。

我有 Model_Artist (Artist.php) 文件:

class Model_Artist extends Zend_Db_Table_Abstract
{
    protected $_name = 'artist';
    protected $_dependentTables = array('Model_ArtistAlbums');
    public function fetchArtistss()
    {
        $select = $this->select();
        return $this->fetchAll($select);
    }
}

到 Model_ArtistAlbums (ArtistAlbums.php) 文件

class Model_ArtistAlbums extends Zend_Db_Table_Abstract
{
    protected $_name = 'albums';

    protected $_referenceMap = array(
        'Artists' => array(
            'columns'       => 'alb_art_id',
            'refTableClass' => 'Model_Artist',
            'refColumns'    => 'art_id'
        )
    );
    // etc
}

在我的控制器中:

public function indexAction()
{
    /* THIS WORKS
    $art = new Model_Artist();
    $artRowset = $art->find(1);
    $art1 = $artRowset->current();
    $artalbums = $art1->findDependentRowset('Model_ArtistAlbums');
    foreach($artalbums as $album){
        echo $album->alb_title."<br>";
    }
    */
    $arts = new Model_Artist();
    $this->view->artists = $arts->fetchArtists();
}

在视图文件中:

$this->partial()->setObjectKey('artist');
echo $this->partialLoop('admin/list-artists.phtml', $this->artists);

但在艺术家/list-artists.phtml 中有这段代码:

foreach($this->artist->findDependentRowset('albums') as $album):
// other stuff
endforeach;

我得到这个错误:

致命错误:调用成员函数 findDependentRowset() 在非对象上

var_dump$this-&gt;artist = NULL

【问题讨论】:

    标签: php zend-framework zend-view


    【解决方案1】:

    在你调用视图中:

    <?php $this->partialLoop()->setObjectKey('artist'); ?>
    <?php echo $this->partialLoop('yourpartial.phtml', $artists); ?>
    

    注意 - 我相信这会更改 partialLoop 帮助器实例的全局对象键,因此您可能想要选择比 artist 更通用的东西,或者如果您稍后在同一视图中将 partialLoop 用于其他东西,请记住重置它.

    在你的部分:

    <?php foreach($this->artist->findDependentRowSet('Albums') as $album): ?>
     <!-- looping stuff here -->
    <?php endforeach; ?>
    

    检查 Zend_Db_Table_Row 的 docs/api 以了解根据您的项目模型命名约定,findDependentRowset 的实际参数应该是什么。如果您尚未定义 _referenceMap,您可能还需要在表类中设置一些内容。

    【讨论】:

    • 奇怪,目前我收到此错误:“消息:在注册表中找不到名称为 'FindDependentRowset' 的插件”
    • oh ok $this 必须引用视图实例,我的大“duh”请参阅编辑。
    • 很困惑,但可以通过:)。不应该是 partialLoop('yourpartial.phtml', $this->artists); ?> ?否则我会得到一个 foreach 错误
    • 绝对正确。那是我的错误......再次。我不知道我是帮助还是伤害! ;-)
    • 刚刚意识到它是什么,不确定你是否在某个时候更改了它,或者我只是复制错了但我有 $this->partial()->setObjectKey('artist') 而不是 $ this->partialLoop()->setObjectKey('artist');
    猜你喜欢
    • 2019-04-21
    • 1970-01-01
    • 2010-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多