使用Zend_Db_Table在Zend Framework中使用CakePHP样式数据库查询结果?

时间:2012-01-09 16:38:37

标签: zend-framework cakephp relational-database zend-db zend-db-table

如果你有一个复杂的SQL查询涉及许多连接(例如返回文章及其关联的多个标签),那么Zend Framework中的任何东西都会产生可爱的CakePHP样式数据库结果:

Array
(
    [0] => Array
        (
            [ModelName] => Array
                (
                    [id] => 83
                    [field1] => value1
                    [field2] => value2
                    [field3] => value3
                )

            [AssociatedModelName] => Array
                (
                    [id] => 1
                    [field1] => value1
                    [field2] => value2
                    [field3] => value3
                )

        )
)

我不介意它是一个对象而不是一个数组,我只是想知道如果使用Zend_Db_Table构建一个SELECT JOIN查询,我可以节省一些腿部工作并获得一些格式良好的结果。

以下是我用于构建查询的代码类型:

$select = $db->select(Zend_Db_Table::SELECT_WITH_FROM_PART);
$select->from('tableName','fieldName')
     ->join('joinTable', 'joinTable.keyId = tableName.keyId',array())
     ->where('tableName.userId = ?', $userId);
$resultSet = $db->fetchAll($select);

1 个答案:

答案 0 :(得分:1)

没有像你所习惯的数据那样漂亮。 普通的Result是一个rowset对象,但 - > toArray()可用于大多数* Zend_DbTable_Abstract *方法。

使用Zend_debug :: dump()截断并转储 $ result-> toArray()

Lead Tracks array(7) {
  [0] => array(9) {
    ["trackid"] => string(2) "24"
    ["weekendid"] => string(1) "8"
    ["shiftid"] => string(1) "1"
    ["bidlocationid"] => string(1) "1"
    ["qty"] => string(1) "2"
    ["lead"] => string(1) "1"
    ["bidloc"] => string(14) "out of service"
    ["deptcode"] => string(3) "491"
    ["stationid"] => string(1) "1"
}

查询:

where = $this->select(Zend_Db_Table::SELECT_WITH_FROM_PART)
                     ->setIntegrityCheck(FALSE);
    $where->where('track.bidlocationid = ?', $bidlocationId)
          ->where('lead = ?', $lead)
          ->join('bidlocation', 'bidlocation.bidlocationid = track.bidlocationid')
          ->where('bidlocation.stationid = ?', $stationId)
          ->order('shiftid ASC')
          ->order('weekendid ASC');

    $result = $this->fetchAll($where);
抱歉,只是效用:)