数据模型

数据模型继承自 Illuminate\Database\Eloquent\Model,因此可以使用 Eloquent ORM 所有方法,并且支持部分三方扩展包。

定义模型

我们创建了一个名为 Example 的模型类,继承自 Dux\Database\Model (该类为 Eloquent ORM 的继承类)。

通过 $table 属性,我们指定了数据表名,一个模型即为一张数据表。

<?php

namespace App\Example\Models;

use Illuminate\Database\Eloquent\Model;

class Example extends Model
{
    public $table = 'example';
}

定义字段

使用 migration 继承方法,我们可以针对该模型表进行字段和修改,可用字段类型请参考 laravel 文档

<?php

namespace App\Example\Models;

use Illuminate\Database\Eloquent\Model;

class Example extends Model
{
    public $table = 'example';
    public function migration(Blueprint $table)
    { 
        $table->id();
        $table->string("name")->comment("名称");
        $table->timestamps();
    }
}

初始数据

使用 seed 继承方法,我们可以对这个表在第一次同步时加入初始化数据:

<?php

namespace App\Example\Models;

use Illuminate\Database\Eloquent\Model;

class Example extends Model
{
    public $table = 'example';
    
    public function migration(Blueprint $table)
    { 
        $table->id();
        $table->string("name")->comment("名称");
        $table->timestamps();
    }
    
    public function seed(Connection $db) {
        $db->table($this->table)->insert([
            'name' => 'test',
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    }
}

同步模型

我们可以使用 dux 命令行工具将数据模型同步至数据库中,该操作不会对已有表造成损耗,会对已有字段进行修改或者增加。

定义注解

同步模型时需要对模型进行注解来标记该模型需要同步:

<?php

namespace App\Example\Models;

use Illuminate\Database\Eloquent\Model;
use Dux\Database\Attribute\AutoMigrate;  
#[AutoMigrate] class Example extends Model
{
    public $table = 'example';
    
    public function migration(Blueprint $table)
    { 
        $table->id();
        $table->string("name")->comment("名称");
        $table->timestamps();
    }
    
    public function seed(Connection $db) {
        $db->table($this->table)->insert([
            'name' => 'test',
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    }
}

同步数据库

使用下面命令将应用模块 example 进行同步至数据库。

Linux + Macos
windows
./dux db:sync example

同步后请打开数据库工具查看数据库结构是否一致。

模型方法

因为使用 Eloquent ORM 作为数据库模型操作所有操作方法和模型关联,如下:


// 查询所有数据
$list = \App\Example\Models\Example::query()->get();

// 查询单条数据
$list = \App\Example\Models\Example::query()->find(1);

// 创建数据
\App\Example\Models\Example::query()->create([
    'name' => 'text'
]);

// 修改数据
\App\Example\Models\Example::query()->where('id', 1)->update([
    'name' => 'text'
]);

// 删除数据
\App\Example\Models\Example::query()->where('id', 1)->delete();

触发事件

数据库模型全局定义了一套方法来进行事件调度的扩展:

事件名

事件名使用 model.类名 结构进行组合,如下示例来代表 Example 的模型事件:

model.App\Example\Models\Example

事件监听

使用事件监听器我们可以针对任意模型的各个事件 (如 curd 等) 进行注册监听:

<?php

namespace App\Example\Listener;

use Dux\Database\DatabaseEvent;

class ModelListener
{
    #[Listener(name: 'model.App\Example\Models\Example')]
    public function data(DatabaseEvent $event): void
    {
        $event->saved(function($model) {
            ...
        });
    }

}

事件触发

监听后在模型对应的操作事件时会触发注册监听的函数,如 saved 等。