在Symfony 2中使用原生SQL

在任氏有无轩站点中,有一个页面是用来给我自己看书籍详情页面的访问记录的,这个页面中需要做一些统计,比如:最近访问的是哪些书籍?访问量最大的是哪些?每天的访问量有多少?

前两个功能都很容易实现,我也以为第三个功能也很容易实现。

但事实并非如此。

第三个功能的实现用原生SQL来做很简单:select count(..), date(from_unixtime(...) ... group by ...就可以了。

但是SF2中的Doctrine不支持date/from_unixtime函数——这点很奇怪!

所以必须使用所谓原生SQL,而在SF2/Doctrine下使用原生SQL,按照官方文档,需要进行所谓ResultSetMapping,这是一个技术活。

我在SF2的官方论坛发帖求救,终于得到了解决:

public function getVisitCountByDay()
    {
        $em = $this->getEntityManager();
        $q=$em->getConnection()->prepare('select count(v.bid) vc, date(from_unixtime(v.visitwhen+24*60*60)) vd from book_visit v group by vd order by vd');
        $q->execute();
        return $q->fetchAll();
    }

这真是意料之外的种种无奈啊!

Comments

One response to “在Symfony 2中使用原生SQL”

Leave a Reply to Guns Wang Cancel reply

Your email address will not be published. Required fields are marked *