How to run raw SQL Query with Zend Framework 2

后端 未结 4 1631
离开以前
离开以前 2020-12-30 04:14

Is there a way to execute a SQL String as a query in Zend Framework 2?

I have a string like that:

$sql = \"SELECT * FROM testTable WHERE myColumn = 5         


        
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-30 04:57

    If you have EntityManager $em on your hands, you can do something like this:

       $select = $em->getConnection()->executeQuery("
            SELECT a.id, a.title, a.announcement, asvc.service_id, COUNT(*) AS cnt,
                GROUP_CONCAT(asvc.service_id SEPARATOR \", \") AS svc_ids
            FROM article AS a
            JOIN articles_services AS asvc ON asvc.article_id = a.id
            WHERE
            asvc.service_id IN (
                SELECT tsvc.service_id
                FROM tender AS t
                JOIN tenders_services AS tsvc ON tsvc.tender_id = t.id
                WHERE t.id = :tenderId
            )
            GROUP BY a.id
            ORDER BY cnt DESC, a.id DESC
            LIMIT :articlesCount
        ", [
            'articlesCount' => 5,
            'tenderId' => $tenderId,
        ], [
            'articlesCount' => \PDO::PARAM_INT,
        ]);
    
        $result = $select->fetchAll(); // <-- here are array of wanted rows
    

    I think this way to execute complex queries is best for Zend. But may be I'm not very smart in Zend still. Will glad to see if it helps to someone.

提交回复
热议问题