Zend Framework 2 SQL加入问题

时间:2017-01-20 03:32:54

标签: mysql zend-framework

我试图在Zend Framework 2的SQL类中使用两个左外连接,但由于某种原因,它没有返回一个结果,但另一个结果正常。我在MySQL Workbench中运行了实际的SQL,它就像我想要的那样返回,但它没有使用Zend Framework。这是我的代码:

Pure SQL:

  SELECT groups.group_name, members.username, groups.id FROM groups
  LEFT OUTER JOIN group_admins ON groups.id = group_admins.group_id
  LEFT OUTER JOIN members ON group_admins.user_id = members.id
  WHERE group_admins.user_id = " . parent::getUserId()['id']

这会返回我希望的结果(可以在这里看到:http://imgur.com/8ydmn4f

现在,这是我已经实施的Zend Framework 2代码:

$select_admins = new Select();

$select_admins->from(array(
    'g' => 'groups',
))
->join(array(
    'ga' => 'group_admins'
),  'g.id = ga.group_id')
->join(array(
    'm' => 'members'
),  'ga.user_id = m.id', array('username'))
->where(array('ga.user_id' => parent::getUserId()['id']));


$query_group_admin = parent::$sql->getAdapter()->query(parent::$sql->buildSqlString($select_admins), Adapter::QUERY_MODE_EXECUTE);

$group_admins = array();

foreach ($query_group_admin as $group_admin) {
    $group_admins[] = $group_admin;
}

// get the group members
$select = new Select();

$select->from(array(
    'g' => 'group_members'
))
->join(array(
    'm' => 'members'
), 'g.member_id = m.id')
->join(array(
   'grp' => 'groups'
), 'g.group_id = grp.id')
->where(array(
    'g.group_id' => $group_id
));

$query = parent::$sql->getAdapter()->query(parent::$sql->buildSqlString($select), Adapter::QUERY_MODE_EXECUTE);

$member_username = array();

foreach ($query as $member) {
    $member_username[] = $member['username'];
}



// get the rest of the group info
$fetch = $this->gateway->select(array(
    'id' => $group_id
));

$row = $fetch->current();

if (!$row) {
    return false;
}

return array(
    'admins'  => implode(", ", $group_admins),
    'members' => implode(", ", $member_username),
    'info' => $row
);

控制器:

public function grouphomeAction()
{
    $id = $this->params()->fromRoute('id', 0);

    if (0 === $id) {
        return $this->redirect()->toRoute('members/groups', array('action' => 'index'));
    }

   if (!$this->getGroupsService()->getGroupInformation($id)) {
       return $this->redirect()->toRoute('members/groups', array('action' => 'index'));
   }

   return new ViewModel(array('group_info' => $this->getGroupsService()->getGroupInformation($id)));
}

但是,这仅显示组名,组创建者和组成员,但将组管理员字段留空。

这是返回的数组的print_r结果:

Array ( [admins] => [members] => jimmysole, fooboy [info] => ArrayObject Object ( [storage:ArrayObject:private] => Array ( [id] => 2 [group_name] => Tim's Group [group_creator] => timlinden [group_created_date] => 2017-01-16 17:39:56 ) ) )

如果有帮助,这里还有一个屏幕截图 - http://imgur.com/xUQMaUu

任何帮助将不胜感激!

感谢。

1 个答案:

答案 0 :(得分:0)

基本上你的联盟是INNER JOINS ......我知道......你现在必须讨厌Zend:p。默认情况下,它们是INNER JOINS,所以我认为这是错误的。所以尝试指定联接的类型,你应该没事。您可以在此处找到更多示例:examples

$select12->from('foo')->join('zac', 'm = n', array('bar', 'baz'), Select::JOIN_OUTER);