lumax/aurora-db

为 Luma 框架构建的独立数据库组件。

2.7.3 2024-08-27 22:50 UTC

README

Version 2.7.3 PHP Coverage 89.67% License GPL--3.0--or--later

小巧但强大的 PHP 数据库组件。

安装

composer require lumax/aurora-db

使用

在应用程序入口处,连接到您的数据库

use Luma\AuroraDatabase\DatabaseConnection;
use Luma\AuroraDatabase\Model\Aurora;
 
$databaseConnection = new DatabaseConnection(
    'mysql:host=localhost;port=3306;',
    'username',
    'password'
);

以最简单形式,我们可以使用上面的 DatabaseConnection 实例来获取 PDO 数据库连接

$pdo = $databaseConnection->getConnection();

这允许您使用 Aurora 模型通过单个共享连接与数据库交互。

《Aurora》模型

创建数据库表

Aurora 模型是一个专门设计用来与相应的数据库表交互的实体。一个 Aurora 模型的实例与其对应的数据库表中的一行相对应。

以下是一些表

CREATE TABLE User (
    intUserId int(11) auto_increment not null primary key,
    strUsername varchar(60) not null
);

CREATE TABLE Article (
    intArticleId int(11) auto_increment not null primary key,
    strTitle varchar(255) not null,
    intAuthorId int(11) not null,
    foreign key (intAuthorId) references User(intUserId)
);

创建 Aurora

我们可以创建以下 Aurora 模型,这将使我们能够在这些表中创建、检索、更新和删除记录。

use Luma\AuroraDatabase\Attributes\Column;
use Luma\AuroraDatabase\Attributes\Identifier;
use Luma\AuroraDatabase\Attributes\Schema;
use Luma\AuroraDatabase\Model\Aurora;

class User extends Aurora
{
    #[Identifier]
    #[Column('intUserId')]
    protected int $id;

    #[Column('strUsername')]
    private string $username;

    /**
     * @return string
     */
    public function getUsername(): string
    {
        return $this->username;
    }
}
use Luma\AuroraDatabase\Attributes\Column;
use Luma\AuroraDatabase\Attributes\Identifier;
use Luma\AuroraDatabase\Attributes\Schema;
use Luma\AuroraDatabase\Model\Aurora;

class Article extends Aurora
{
    #[Identifier]
    #[Column('intArticleId')]
    protected int $id;

    #[Column('strTitle')]
    private string $title;

    #[Column('intAuthorId')]
    private User $author;

    /**
     * @return string
     */
    public function getTitle(): string
    {
        return $this->title;
    }
    
    /**
    * @return string
    */
    public function setTitle(): string
    {
        $this->title = $title;
    }

    /**
     * @return User
     */
    public function getAuthor(): User
    {
        return $this->author;
    }
}

所有 Aurora 模型都有一个 getId() 方法,它返回具有 #[Identifier] 属性的属性的值。 标识符必须是 protected 并且是有效 Aurora 模型的一部分。 所有其他希望映射到数据库列的属性应使用 #[Column($name)] 属性。

可空列

如果您的数据库表包含任何可空列,则确保相关的属性已被指定为可空类型非常重要

#[Column('myNullableColumn')]
private ?string $nullableColumn;
一对多关系

为了处理一对多关系,例如获取由 User 创建的所有 Article 模型,我们可以在 User 模型中添加一个属性来保存我们的文章

#[AuroraCollection(class: Article::class, property: 'author')]
private Collection $articles;

/**
 * @return Collection<Article>
 */
public function getArticles(): Collection
{
    return $this->articles;
}

就是这样简单,现在从 User 实例调用 getArticles() 将返回包含该用户所写所有文章的 Collection

表 & 架构

默认情况下,与您的 Aurora 类关联的表名将与您的类名相同 - 所以在这个例子中是 UserArticle。此外,您的类不会设置任何架构 - 输出查询将类似于这样 SELECT * FROM User ...

您可能希望指定一个架构和表名

#[Schema('Core')]
#[Table('User')]
class User extends Aurora {
    ...
}

这将创建/运行查询,类似于这样 SELECT * FROM Core.User ...

CRUD 方法

让我们向创建的表中添加一些新记录

// Create a new user. Not yet saved to the database.
$user = User::create([
    'username' => 'Dan',
]);

// Save to the database.
$user->save();

// Create a new article and save to the database.
Article::create([
    'title' => 'Hello, Aurora!',
    'author' => $user,
])->save();

然后我们可以检索它们

$user = User::find(1);

// Find by takes the PROPERTY name (not column name, unless they're the same of course)
$user = User::findBy('username', 'Dan');

$article = Article::getLatest();

$articles = Article::all();

$userCount = User::count();

save() 方法还可以用于更新现有记录

$article = Article::find(1);

$article->setTitle('My Updated Article Title');

$article->save();

我们还可以删除现有记录

$article = Article::find(1);

$article->delete();

分页

Aurora 还允许您对数据进行分页

$articles = Article::paginate($page = 1, $perPage = 10, $orderBy = null, $orderDirection = null);

查询构建器

Aurora 模型包括一个方便的查询构建器。一些重要说明

为了执行任何查询构建器语句并检索结果,您必须调用 get 方法。

所有查询构建器结果都返回指定的列以及它们的主标识符,因此不需要指定。

在调用 get() 之后,有 3 种可能的返回类型

  • 一个 结果返回时,这返回为调用类的实例。
  • 多个 结果返回时,这返回包含调用类实例的数组。
  • 没有 结果返回时,查询构建器返回 NULL。

以下是您可以使用的一些方法

// Creating some new records in a blank table (with added email address column)
User::create('User One', 'user1@test.com')->save();
User::create('User Two', 'user2@test.com')->save();
User::create('User Three', 'user3@test.com')->save();

// Return all users as an array
$user = User::select()->get(); 

// Specify columns
$users = User::select('email')->get();

$users[0]->getEmailAddress(); // user2@test.com
$users[0]->getId(); // 2 (we always populate the primary key)
$users[0]->getUsername(); // fails

// Add a where clause
$user = User::select()->whereIs('username', 'User Three')->get();

$user->getId(); // 3

// We can chain whereIs (and other WHERE methods), which automatically converts them to an AND
// Returns NULL as no rows match this query
$user = User::select()->whereIs('username', 'User Three')->whereIs('id', 2)->get();

// We can specify not conditions
$users = User::select()->whereNot('username', 'User Three')->get();

count($users); // 2

// We can perform whereIn/whereNotIn queries
$user = User::select()->whereNotIn('id', [1, 2])->get();

$user->getId(); // 3

$users = User::select('username')->whereIn('id', [1, 3])->get();

count($users); // 2