mysqlzend-framework2zend-dbzend-db-table

Convert raw sql to ZF2 statement


In zf2, how can i write following mysql query and execute it. ??

SELECT * FROM `user_modules` um JOIN ((SELECT vm.id, vm.module_code, vm.module_title,'video' AS type FROM video_master vm WHERE vm.is_deleted = 0) UNION (SELECT sm.id, sm.module_code, sm.module_title, 'slideshow' AS type FROM slideshow_master sm WHERE sm.is_deleted = 0) result ON um.module_id = result.id 
WHERE um.user_id='3' 

Solution

  • I found solution!!

    $userId   = '1';
    
    $select = "SELECT * FROM `user_modules` um JOIN ((SELECT vm.id, vm.module_code, vm.module_title, 'video' AS type FROM video_master vm WHERE vm.is_deleted = 0) UNION (SELECT sm.id, sm.module_code, sm.module_title, 'slideshow' AS type FROM slideshow_master sm WHERE sm.is_deleted = 0)) temptable on um.module_id = temptable.id where um.user_id='". $userId ."'";
    
    $resultSet = $this->adapter->query($select);
    return $data = $this->resultSetPrototype->initialize($resultSet->execute())->toArray();
    

    OR else can use ZF2 method:

    $sql = new Sql($this->getAdapter());
    
    $select = $sql->select()->from(array('um' => $this->table));
    

    Get all slideshow modules

    $select1 = $sql->select(array())->from(
                 array("slideshow" =>'slideshow_master'))
              ->columns(array('id','module_code','module_title',"type" => new Expression("'Slideshow'")));
    
    $select1 = $sql->select(array())->from(
                 array("slideshow" =>'slideshow_master'))
              ->columns(array('id','module_code','module_title',"type" => new Expression("'Slideshow'")));
    
    $select1->where("slideshow.is_deleted = 0");
    $select1->order("slideshow.id");
    

    Get all video modules

    $select2 = $sql->select(array())->from(
                  array("video" => 'video_master'))
               ->columns(
                     array('id','module_code','module_title',"type" => new Expression("'Video'")));
    
    $select2->where("video.is_deleted = 0");
    $select2->order("video.id");
    

    union of two first selects

    $select1->combine ( $select2, 'UNION' );
    
    $select->join(array('result' => $select1), "result.id = um.module_id");
    
    $select ->where("um.user_id='". $userId. "'");
    
    $statement = $sql->prepareStatementForSqlObject($select);
    return $this->resultSetPrototype->initialize($statement->execute())->toArray();
    

    Sorry for my typing and formatting.