将原始sql转换为ZF2语句

时间:2016-06-03 07:14:00

标签: mysql zend-framework2 zend-db zend-db-table

在zf2中,如何编写以下mysql查询并执行它。 ??

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' 

1 个答案:

答案 0 :(得分:1)

我找到了解决方案!!

$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();

或者可以使用ZF2方法:

$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");

获取所有视频模块

$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");

两个第一次选择的联合

$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();

对不起我的打字和格式化。