2013-06-26 4 views
6

하나의 $ sql 개체 (및 쿼리 (SQL COMMAND) 메서드 사용 안함)를 사용하여 ZF2에 여러 행을 삽입하는 방법이 있는지 알고 싶습니다.ZF2 여러 행 삽입

나는 이런 식으로 뭔가를 시도했지만 작동하지 않습니다 :

public function setAgentProjectLink($IDProject , $IDsAgents) 
{ 
    $values = array() ; 
    foreach ($IDsAgents as $IDAgent): 
    { 
     $values[] = array ('id_agent' => $IDAgent , 'id_projet' => $IDProject) ; 
    } endforeach ; 

    $sql = new Sql($this->tableGateway->adapter) ; 
    $insert = $sql->insert() ; 

    $insert -> into ($this->tableGateway->getTable()) 
      -> values ($values) ; 

    $statement = $sql->prepareStatementForSqlObject($insert); 
    $result = $statement->execute(); 
} 

가 ZF2에서 multyinsert에 대한 일반적인 방법이없는 두 개의 열 (id_agent, id_projet)

+1

데이터베이스 삽입을 사용하여이 작업을 수행하는 일반적인 방법은 다중 삽입이 MySQL의 기능이며 표준 SQL 유형의 삽입이 아니기 때문입니다. – Andrew

+0

응답 해 주셔서 감사합니다. (답변이 늦어서 죄송합니다.) 이 경우 zf2 SQL 트랜잭션을 사용하는 것이 더 나은 솔루션을 찾았습니다. – aramir

+0

예, zf2 sql 트랜잭션을 사용한 후에는 $ insert -> into ($ this-> tableGateway-> getTable()) -> values ​​($ 값, '설정'); – prava

답변

4

와 데이터베이스에 값을 삽입하려고 그러나 mysql을 사용하고 있고 다른 데이터베이스로 변경할 계획이 없다면 직접 멀티 인서트 함수를 작성했다.

$data은 키, 값 쌍의 배열 배열이다.

protected function multiInsert($table, array $data) 
    { 
     if (count($data)) { 
      $columns = (array)current($data); 
      $columns = array_keys($columns); 
      $columnsCount = count($columns); 
      $platform = $this->db->platform; 
      array_filter($columns, function ($index, &$item) use ($platform) { 
       $item = $platform->quoteIdentifier($item); 
      }); 
      $columns = "(" . implode(',', $columns) . ")"; 

      $placeholder = array_fill(0, $columnsCount, '?'); 
      $placeholder = "(" . implode(',', $placeholder) . ")"; 
      $placeholder = implode(',', array_fill(0, count($data), $placeholder)); 

      $values = array(); 
      foreach ($data as $row) { 
       foreach ($row as $key => $value) { 
        $values[] = $value; 
       } 
      } 


      $table = $this->db->platform->quoteIdentifier($table); 
      $q = "INSERT INTO $table $columns VALUES $placeholder"; 
      $this->db->query($q)->execute($values); 
     } 
    } 
+0

매력처럼 작동합니다 .... 정말 고마워요! –