查询生成器,如Drupal's数据库API


Query builder like Drupal's Database API?

我正在寻找普通mysql和mysqli的分支,并尝试使用一些更好的方式进行数据库访问,而不是DAO层(这里增加了太多的复杂性)。

当我做Drupal开发时,我不得不使用它的数据库API。大多数时候,它真的很好,允许您构建查询并让它为您转义所有内容。PDO和mysql准备好的语句无法接近Drupal数据库API的优美和整洁。我仍然不知道如何,例如,在mysqli中使用一个准备好的语句来插入未知大小的行,而不需要自己构建查询,这违背了准备好的语句的目的。它只是挡了我的路

Drupal API的实际代码示例

$query = db_select('tcsync_queue', 'q')
    ->condition('q.id', $post["tcsync_lastrecord"], '>')
    ->fields('q', array('id', 'uid', 'type', 'name', 'data'))
    ->execute();
foreach ($query as $item) {
    $updateitem = array(
        "id" => $item->id, 
        "uid" => $item->uid, 
        "type" => $item->type, 
        "name" => strtoupper($item->name),
        "data" => $item->data);
    ....
}

是否有一个查询生成器完成一些接近Drupal的查询生成器?

您可能正在寻找NotORM­主页 PHP库。它非常轻量级(我认为这是您所要求的),并且是一个独立的组件,因此您没有那么多集成的负担。

它使用PDO作为连接对象:

include "NotORM.php";
$pdo = new PDO("mysql:dbname=software");
$db = new NotORM($pdo);

所以它支持PDO中可用的任何数据库。

您可以简单地运行查询,下面是一个带有应用程序表的数据库示例:

foreach ($db->application() as $application) { // get all applications
    echo "$application[title]'n"; // print application title
}
当涉及到where和limits时,它是这样工作的:
$applications = $db->application()
    ->select("id, title")
    ->where("web LIKE ?", "http://%")
    ->order("title")
    ->limit(10)
;
foreach ($applications as $id => $application) {
    echo "$application[title]'n";
}

它做得很好,这不是类似的代码,例如codeigniter中的sql代码的情况。

我想你会喜欢Doctrine 2的DBAL。我将为您提供一些示例代码:

    $locationIds = array(1,2,3,4,5,6,7);
    $locationTreeDepthQb = $conn->createQueryBuilder();
    $locationTreeDepthQb->select("COUNT(*) as count")
        ->from('location_tree_data', 'd')
        ->where("d.tree_depth >= 2")
        ->andWhere("d.tree_id IN (?)");
    $stmt = $conn->executeQuery($locationTreeDepthQb->getSQL(), array($locationIds), array(Connection::PARAM_INT_ARRAY));
    $res = $stmt->fetch();

请注意,在这个查询生成器中,为"IN"SQL语句传递数组是多么容易。

文档可以在这里找到:http://www.doctrine-project.org/docs/dbal/2.2/en/

CodeIgniter做得很好:

选择:

$this->db->select('title')->from('mytable')->where('id', $id)->limit(10, 20);
$query = $this->db->get();
插入:

$this->db->set('title',$title)->insert('mytable');
更新:

$this->db->where('id', $id)->set('title',$title)->update('mytable');

见:http://codeigniter.com/user_guide/database/active_record.html

https://github.com/kenaniah/insight/blob/master/classes/query.php可以修改为独立存在。