PHQL "WHERE xxx IN ()" can get only 1 data

时间:2015-10-30 23:36:18

标签: php mysql phalcon

I'm creating a RESTful API with Phalcon. I want to get some data from "Shop" table by IDs. PHP code: $app->post('/api/shops/search', function () use ($app) { $ids_shop = $app->request->getJsonRawBody(); $ids = array(); foreach($ids_shop as $id){ $ids[] = $id->id_shop; } $ids_str = implode(",", $ids); $shops = getShopsData($ids_str, $app); return $shops; }); function getShopsData($ids_shop, $app) { $phql = "SELECT * FROM Shops WHERE Shops.id IN ( :ids: )"; $shops = $app->modelsManager->executeQuery($phql, array( 'ids' => $ids_shop )); return $shops; } Test: curl -i -X POST -d '[{"id_shop":1},{"id_shop":2}]' http://localhost/sample/api/shops/search However I can get only one data whose id is 1. And I also tried it: curl -i -X POST -d '[{"id_shop":2},{"id_shop":1}]' http://localhost/sample/api/shops/search This returns one data whose id is 2. Why cannot I get multiple data? My log says $ids_str = "1,2", so I think phql query might be correct...

1 个答案:

答案 0 :(得分:0)

由于很少有适用于您的示例的PDO和PHQL herehere的示例,Phalcon queryBuilder机制中还有一种方法可以实现:

$builder = $this->modelsManager->createBuilder();
$builder->addFrom('Application\Entities\KeywordsTrafficReal', 'tr')
        ->leftJoin('Application\Entities\Keywords', 'kw.id = tr.keyword_id', 'kw')
        ->inWhere('keyword_id', self::$keywords) // <<< it is an array!
        ->betweenWhere('traffic_date', self::$daterange['from'], self::$daterange['to']);
据我所知,

inWhere方法只能通过queryBuilder访问,它的工作方式与提到的PDO示例IN (?, ?, ?)完全相同。但是您不需要手动实现它。

您也可以跳过部分创建PHQL并直接驱动创建SQL查询,但需要花费自己的验证费用。

$realModel = new KeywordsTrafficReal();

$sql = sprintf('SELECT * '
            .  'FROM keywords_traffic_real tr '
            .  'LEFT JOIN keywords kw '
            .  'ON kw.id = tr.keyword_id '
            .  'WHERE tr.keyword_id IN(%s) '
            .  "AND traffic_date BETWEEN '%s' AND '%s' ",
        join(',', self::$keywords), self::$daterange['from'], self::$daterange['to']);

$results = new \Phalcon\Mvc\Model\Resultset\Simple(null, $realModel, $realModel->getReadConnection()->query($sql));