marcel-maqsood/database-connector

持久PDO对象用于连接数据库并在运行时生成SQL语句。

v1.0.1.8 2024-07-17 11:16 UTC

This package is auto-updated.

Last update: 2024-09-17 11:40:16 UTC


README

您可以使用以下命令安装此包:composer require marcel-maqsood/database-connector

配置

我们的Database-Connector配置非常简单。

'persistentpdo' => [
    'dsn' => 'mysql:host=localhost;dbname=report_portal;port=3306', //- DSN string to connect to your database.
    'username' => 'root', //- The username which you want to use to connect.
    'password' => 'root' //- The password that your database-user has.
],

此外,您可以将我们的PersistentPDO添加到您的ConfigProviders中的任何一个,或者直接添加到您的应用程序的config\autoload\dependencies.global.php中。

'dependencies' => 
[
    'aliases' => 
    [
    ],
    'invokables' => [],
    'factories' => 
    [
        PersistentPDO::class => PersistentPDOFactory::class,
        PDORepository::class => PDORepositoryFactory::class,
    ],
],

ConfigProviders的语法相同,但通过将其添加到依赖中,您将始终在任何应用模块中访问它,而无需再次考虑其配置。

功能

get()

根据指定条件从数据库中检索数据。

此函数构造并执行一个SQL查询以从数据库中检索数据。

它接收以下参数

  • string $field - 要在哪个字段中搜索$identifier。
  • string $table - 要搜索的表。
  • array|string $conditions - 要过滤结果的数组或字符串条件。
  • array $joins - 一个数组,定义应使用哪些表来使用某些列。
  • array $groupDetails - 一个数组,定义如何对多行值进行分组。
  • boolean $debug - 如果生成的SQL应打印以进行调试。
条件在"WHERE"之后附加,不要包括它。

第一个条件不应包含'logicalOperator'键,因为没有先前的条件可以与之结合,如果定义了它,也不会使用它。示例

$conditions = [
    [
        'field' => 'tableCol',
        'logicalOperator' => 'AND' // The logical operator to combine conditions: 'AND' or 'OR' (wont be used, as its the first condition)
        'operator' => 'LIKE',  // The operation that this condition must match.
        'queue' => 'admin',    // The value to look for in the 'name' field.
        'wildcard' => 'both'   // The mode for character matching: before | after | both | none .
    ]
];
$conditions could be a ```string``` aswell, example: ```"name = 'test'"```

此函数返回一个string(字段值)或null,如果没有找到符合您条件的行。

getAll()

有关详细信息,请参阅get();因为这个方法使用相同的语法。

get()和getAll()之间的主要区别是显而易见的:getAll()检索符合您条件的所有行,而不仅仅是第一行。

它返回null或一个填充有键和值的数组,其中每个值都是一个string

getAllBase()

getAll()和getAllBase()之间的主要区别是:getAllBase()需要一个SQL字符串,而不是普通的表名、条件、连接或任何其他内容。

当您需要执行边缘情况查询时,例如检查存在于一个表但不存在于另一个表中的项时,这非常有用,因为这不是我们的其他函数所支持的,因此需要自定义SQL语句。

就像getAll()一样,它返回null或一个填充有键和值的数组,其中每个值都是一个string

update()

根据特定条件更新数据库中的数据。

它接收以下参数

  • array $updates - 包含字段和新值的数组
    [
      'fieldName' => 'value',
      //...
    ]
    
  • boolean $debug - 如果生成的SQL应打印以进行调试。
  • array|string $conditions - 此函数使用与get()相同的语法。

此函数返回一个布尔值:给定语句的结果。

insert()

根据特定条件在数据库中插入数据。

它接收以下参数

  • string $table - 应添加此条目的表
  • array $inserts - 包含字段和值的数组。
  • boolean $debug - 如果生成的SQL应打印以进行调试。

$inserts数组定义与update()中的$updates数组相同。

此函数要么返回插入行的ID,要么在语句有问题时返回false。

delete()

根据特定条件删除数据库中的数据。

它接收以下参数

  • string $table - 应添加此条目的表
  • array|string $conditions - 此函数使用与get()相同的语法。

此函数返回一个布尔值:给定语句的结果。