2016-09-17 75 views
2

我有一個簡單的索引操作:ZF2如何模型類的子項添加到主模型

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

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

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

將獲得接收機(主表的子項)看起來是這樣的:

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; 
} 

這使我看中的錯誤

這個結果是一個只進結果集,調用 前進後退()不是蘇pported。

所以,我想我的問題是這樣的:當我做結果集的提取時,它會在模型​​類中提交,這要歸功於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()方法需要的?也許它可以集成在1個查詢中。只要使用型號ReminderReceiver,就可以。

回答

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; 
}