You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
65 lines
1.8 KiB
65 lines
1.8 KiB
<?php
|
|
|
|
namespace App\Console\Commands; // 定义命名空间
|
|
|
|
use App\Models\User; // 引入 User 模型
|
|
use Illuminate\Console\Command; // 引入 Laravel 的 Command 基类
|
|
use Illuminate\Database\Eloquent\Model; // 引入 Eloquent 模型基类
|
|
use Illuminate\Support\Collection; // 引入 Collection 类
|
|
|
|
/**
|
|
* 导出数据库命令
|
|
*
|
|
* 该命令用于将用户数据导出到 JSON 文件中。
|
|
*/
|
|
class ExportDatabaseCommand extends Command
|
|
{
|
|
/**
|
|
* 控制台命令的名称和签名
|
|
*
|
|
* @var string
|
|
*/
|
|
protected $signature = 'moon:export'; // 定义命令的名称和签名
|
|
|
|
/**
|
|
* 控制台命令的描述
|
|
*
|
|
* @var string
|
|
*/
|
|
protected $description = '导出数据到 json 文件'; // 描述该命令的用途
|
|
|
|
/**
|
|
* 创建一个新的命令实例.
|
|
*
|
|
* @return void
|
|
*/
|
|
public function __construct()
|
|
{
|
|
parent::__construct(); // 调用父类构造函数
|
|
}
|
|
|
|
/**
|
|
* 执行控制台命令
|
|
*
|
|
* 该方法执行导出用户数据的逻辑,将数据保存为 JSON 格式。
|
|
*
|
|
* @return mixed
|
|
*/
|
|
public function handle()
|
|
{
|
|
// 查询所有用户并按创建时间升序排列
|
|
$users = User::query()
|
|
->oldest() // 按照创建时间升序排列
|
|
->get() // 获取所有用户记录
|
|
->transform(function (User $user) {
|
|
// 先排除自身主键
|
|
$user->offsetUnset($user->getKeyName()); // 从用户模型中移除主键字段
|
|
|
|
return $user; // 返回处理后的用户对象
|
|
});
|
|
|
|
// 将用户数据转换为 JSON 格式并写入指定文件
|
|
file_put_contents(\UsersTableSeeder::DATA_PATH, $users->toJson(JSON_UNESCAPED_UNICODE)); // 保存 JSON 数据到文件
|
|
}
|
|
}
|