0

基本上,我想要一个新闻页面,其中包含基于月份和年份的侧列中的存档列表。例如 2012 年 6 月。该表名为“新闻”,包含 news_id、news_title、news_entry、updated、created 列。更新和创建的是时间戳。现在我正在使用普通的php,如下所示:

mysql_select_db($database_admin_conn, $admin_conn);
$query_getArchives = "SELECT DISTINCT DATE_FORMAT (news.updated, '%M %Y') AS archive, DATE_FORMAT (news.updated, '%Y-%m') AS link FROM news ORDER BY news.updated DESC";
$getArchives = mysql_query($query_getArchives, $admin_conn) or die(mysql_error());
$row_getArchives = mysql_fetch_assoc($getArchives);
$totalRows_getArchives = mysql_num_rows($getArchives);

显示档案栏的代码如下:

<h3>News Archives</h3>
<ul>
<?php do { ?>
<li class="seperator
<?php echo (isset($_GET['archive']) && $_GET['archive'] == $row_getArchives['link'] ? 'currentItem' : '') ?>">
<a href="news.php?archive=<?php echo $row_getArchives['link']; ?>"><?php echo $row_getArchives['archive']; ?></a>
</li>
<?php } while ($row_getArchives = mysql_fetch_assoc($getArchives)); ?>
</ul>

如何在 Zend Framework 的第一个代码块中实现 select 语句,以达到与当前代码输出相同的结果?提前致谢!

4

1 回答 1

0

首先将表类创建到/models/DbTable/Archive.php或使用 zf 命令工具。

class Application_Model_DbTable_Archive extends Zend_Db_Table_Abstract
{
    protected $_name = 'news'; // actual table name here
}

然后使用下面的代码

$table = new Application_Model_DbTable_Archive();

$select = $table->getAdapter()->select()
            ->from(array('news' => $table->info(Zend_Db_Table::NAME)), 
                array(
                    'archive'=>new Zend_Db_Expr('DISTINCT DATE_FORMAT (news.updated, \'%M %Y\')'), 
                    'link'=>new Zend_Db_Expr('DISTINCT DATE_FORMAT (news.updated, \'%Y-%m\')')))
            ->order('news.updated DESC');
// then use $select
$row_getArchives = $table->fetchAll($select);
$totalRows_getArchives  = $row_getArchives ->count();

和视图

foreach($row_getArchives as $row){
    echo $row->link;
}

如果你不想使用表类,试试这个:

$adapter = Zend_Db_Table::getDefaultAdapter();
$select = $adapter->select()
        ->from(array('news' => 'news'), 
            array(
                'archive'=>new Zend_Db_Expr('DISTINCT DATE_FORMAT (news.updated, \'%M %Y\')'), 
                'link'=>new Zend_Db_Expr('DISTINCT DATE_FORMAT (news.updated, \'%Y-%m\')')))
        ->order('news.updated DESC');
// then use $select
$row_getArchives = $adapter->fetchAll($select);
$totalRows_getArchives  = count($row_getArchives);

和视图

foreach($row_getArchives as $row){
    echo $row['link'];
}
于 2013-02-06T18:28:02.987 回答