salemc/typescriptify-laravel-models

将 Laravel 模型转换为 TypeScript 接口

1.0.0 2022-10-18 19:05 UTC

This package is auto-updated.

Last update: 2024-09-17 00:36:20 UTC


README

轻松从 Laravel 模型类生成 TypeScript 接口定义。

用法

php artisan typescriptify:model 命令的 --help 选项列出了可用的子命令

php artisan typescriptify:model --help

Description:
  Convert a model to it's TypeScript definition.

Usage:
  typescriptify:model [options] [--] <model>

Arguments:
  model The fully qualified class name for the model - e.g. App\Models\User

Options:
      --includeHidden[=INCLUDEHIDDEN] Include the protected $hidden properties [default: "false"]
      --includeRelations[=INCLUDERELATIONS] Map foreign key columns to interface definitions [default: "true"]

示例用法

在新的 Laravel 安装上运行 php artisan typescriptify:model \App\Models\User 将生成

interface User {
    id: number;
    name: string;
    email: string;
    email_verified_at: string|null;
    created_at: string|null;
    updated_at: string|null;
}

或者,如果您愿意,可以实例化自己的 TypeScriptifyModel 类版本

use SalemC\TypeScriptifyLaravelModels\TypeScriptifyModel;

echo (new TypeScriptifyModel(\App\Models\User::class))->generate();

关系映射

TypeScriptify Laravel Models 支持 belongsTo 关系映射。

想象一下以下场景

// app/Models/User.php
// columns: id, name, email, password, role_id

public function role(): BelongsTo {
    return $this->belongsTo(Role::class);
}

// app/Models/Role.php
// columns: id, name

public function users(): HasMany {
    return $this->hasMany(User::class);
}

users 表上有一个外键(以及外键约束)role_id

如果生成的 User 接口上没有 role_id: number 属性,而是完整的关联数据集,那不是很好吗?嗯,TypeScriptify Laravel Models 能够识别出 role_id 列应该是 Role 模型,并将其映射到可重用的接口定义中。不幸的是,我们无法确定确切的关联名称;相反,我们根据外键名称为您猜测。

// Automatically generated Role interface.
interface Role {
    id: number;
    name: string;
}

interface User {
    id: number;
    name: string;
    email: string;
    password: string;
    role: Role; // 'guessed' attribute name of 'role' (from 'role_id') with the interface Role, generated above.
}

工作原理

数据库

TypeScriptify Laravel Models 主要通过收集 Laravel 实例配置的数据库中的列数据来工作。收集完成后,它将列类型映射到已知的 TypeScript 类型。这意味着如果您没有数据库列来转换属性,则它不会存在于最终的 TypeScript 接口定义中。

转换

TypeScriptify Laravel Models 还尊重您在正在转换的模型中设置的 可预测 Laravel 转换(特别是 protected $castsprotected $dates)。它将所有已知转换映射到 TypeScript 类型。

注意事项

TypeScriptify Laravel Models 仅能将 可预测 数据类型映射到 TypeScript 类型。《自定义转换》和《自定义访问器》不支持。

如果 TypeScriptify Laravel Models 无法将类型映射到 TypeScript 类型,则将在 TypeScript 接口定义中将值设置为 unknown