ZF2如何将子项的模型类添加到主模型中

时间:2016-09-17 13:24:53

标签: php zend-framework2 models

我有一个简单的索引操作:

$reminders = $this->reminderTable->fetchAll();

foreach ($reminders as $reminder) {
    $reminder->receivers = $this->reminderTable->getReceivers($reminder->id);
}

return new ViewModel(array(
    'reminders' => $reminders
));

get接收器(主表的子项)如下所示:

public function getReceivers($id)
{
    $adapter = $this->tableGateway->getAdapter();
    $receiversTable = new TableGateway('ga_reminders_receivers', $adapter);

    $resultSet = $receiversTable->select(function (Select $select) use ($id) {

        $select->join('ga_users', 'ga_reminders_receivers.receiver_uid = ga_users.uid', array('uid', 'firstname', 'lastname', 'email', 'telephone'), 'left');
        $select->where('ga_reminders_receivers.rid = ' . $id);

    });

    return $resultSet;
}

这给了我一个奇特的错误

  

此结果是仅向前结果集,之后调用rewind()   不支持前进。

所以,我想我的问题是:当我获取结果集时,由于exchangearray(),它会在模型​​类中填充。但是我怎么想用一个子模型列表填充模型属性?

在这种情况下,模型为Reminder

class Reminder { // from the reminders table

public function exchangeArray($data)
{
    $this->id = (!empty($data['rid'])) ? str_pad($data['rid'], 5, '0', STR_PAD_LEFT) : null;
    $this->label = (!empty($data['label'])) ? $data['label'] : null;
    // etc.
    $this->receivers = array(
        new Receiver(1),
        new Receiver(2),
        // list of objects from the reminders_receivers table
    )
}

第二个问题:是否需要单独的getReceivers()方法?也许它可以集成在一个查询中。只要使用模型类ReminderReceiver就可以了。

1 个答案:

答案 0 :(得分:0)

在这种情况下,你必须使用缓冲区。

public function getReceivers($id)
{
    $adapter = $this->tableGateway->getAdapter();
    $receiversTable = new TableGateway('ga_reminders_receivers', $adapter);

    $resultSet = $receiversTable->select(function (Select $select) use ($id) {

        $select->join('ga_users', 'ga_reminders_receivers.receiver_uid = ga_users.uid', array('uid', 'firstname', 'lastname', 'email', 'telephone'), 'left');
        $select->where('ga_reminders_receivers.rid = ' . $id);

    });


    $resultSet->buffer();
    return $resultSet;
}