2016-09-21 42 views
0

我在zf2子查詢中得到sql語法問題我不知道我的查詢有什麼問題。我的查詢關於MySQLzf2 - 子查詢問題在型號

完美的工作在Zend中它顯示了語法錯誤

的SQLQuery

SELECT (SELECT role_name FROM roles WHERE role_id=(SELECT role_id FROM users WHERE id=a.user_id)) AS role,`a`.consultant_id,`a`.*, `c`.`name` AS `name`, `b`.`name` AS `branchname`, `u`.`name` AS `consultantname`, `u`.`role_id` AS `role_id`, `r`.`role_name` AS `rolename` 
      FROM `agents` AS `a` 
      LEFT JOIN `countries` AS `c` ON `c`.`code` = `a`.`country` 
      LEFT JOIN `branches` AS `b` ON `b`.`id` = `a`.`branch_id` 
      INNER JOIN `users` AS `u` ON `u`.`id` = `a`.`consultant_id` 
      INNER JOIN `roles` AS `r` ON `r`.`role_id` = `u`.`role_id` 
    WHERE r.`role_id` IN(5,12,21,25,43,44) AND a.branch_id=63 AND a.consultant_id =2834 
    ORDER BY `a`.`id` ASC 

Zend的查詢

 $rolesSelect = new Select(); 
     $rolesSelect->from(array('r1' => 'roles')); 
     $rolesSelect->columns(array('ro_name'=>'role_name')); 
     $rolesSelect->join(array('u1' =>'users'), 'u1.role_id = r1.role_id', array('')); 
     $rolesSelect->join(array('a1' =>'agents'), 'u1.id = a1.user_id', array('')); 

     $select = new Select(); 
     $select->from(array('a' => 'agents')); 
     $select->columns(array('*','role_name1' => new Expression('?', array($rolesSelect)))); 
     $select->where($conditions); 
     $select->join(array('c' =>'countries'), 'c.code = a.country', array('name'),'left'); 
     $select->join(array('b' =>'branches'), 'b.id = a.branch_id', array('branchname'=>'name'),'left'); 
     $select->join(array('u' =>'users'), 'u.id = a.consultant_id', array('consultantname'=>'name','role_id'=>'role_id')); 
     $select->join(array('r' =>'roles'), 'r.role_id = u.role_id', array('')); 
     $select->order('a.id ASC'); 
     $resultSet = $this->tableGateway->selectWith($select); 
     echo $conditions."<pre>"; 
     print_r($resultSet); 
     die; 
     return $resultSet->buffer(); 
+0

語句無法執行(42000 - 1064 - 您的SQL語法錯誤;檢查與您的MySQL服務器版本相對應的手冊,以便在'AS'''FROM'agents'附近使用正確的語法AS'a' LEFT JOIN'countries' as'c' ON'c'.'code' ='a' .'cou'at line 1) –

+0

我確信我的mysqlquery工作正常,但在zend我無法適應 –

+0

是的,我正在寫模型文件 –

回答

0

可以使用Zend的表達,而不是看以下示例

$select = new Select(); 
      $select->from(array('a' => 'agents')); 
      $select->columns(array('*','consultantname' => new \Zend\Db\Sql\Expression('(SELECT u.name FROM users u WHERE u.id = a.consultant_id)'))); 
      $select->where($conditions); 
      $select->join(array('u' =>'users'), 'u.id = a.user_id', array()); 
      $select->join(array('c' =>'countries'), 'c.code = a.country', array('name'),'left'); 
      $select->join(array('b' =>'branches'), 'b.id = a.branch_id', array('branchname'=>'name'),'left'); 
      $select->join(array('r' =>'roles'), 'r.role_id = u.role_ref_id', array('role_name')); 
      $select->order('a.id ASC'); 
      $resultSet = $this->tableGateway->selectWith($select); 
      //echo "<pre>";print_r($resultSet);die; 
      return $resultSet->buffer();