mstone121/php-object-sql

面向对象的SQL生成方法

v0.3 2021-04-27 02:16 UTC

This package is auto-updated.

Last update: 2024-09-23 20:36:35 UTC


README

PHP中的面向对象SQL生成方法

本项目旨在将面向对象编程的原则应用于SQL查询生成,而无需ORMs的严格要求和复杂的设置。

之前

$query = "SELECT question.id, qr.id, qr.response_label
    FROM questions q
    LEFT JOIN question_responses qr ON qr.question_id = q.id";

if ($questionIds) {
    $query .= "WHERE q.id IN ('" . implode("','", $questionIds) . "')";
}

$query .= " ORDER BY q.id, qr.id";

之后

$query = new QString(
    new QSelect([
        'q.id',
        'qr.id',
        'qr.label'
    ]),
    new QFrom('questions'),
    new QJoinsCollection(
        new QJoinOn(
            'question_responses qr',
            'qr.question_id = q.id',
            'LEFT'
        )
    ),
    new QOrder(['q.id', 'qr.id'])
);

if ($questionIds) {
    $query->addComponent(
        new QWhere(
            new QAnd(
                new QIn('q.id', $questionIds)
            )
        )
    );
}

请注意,在QComponents中对传入的字符串不进行任何检查。这意味着你可能创建如下查询

new QString(
    new QSelect([
        "1; TRUNCATE questions; SELECT *"
    ]),
    new QFrom('questions')
)

并且它将删除questions表中的所有内容。

该库假设你是有意识地使用它,因此赋予你更大的灵活性,同时也赋予你更大的责任。