laravel 利用factory数据填充

本文详细介绍如何在Laravel框架中使用Factory进行数据填充,包括创建账单表、定义模型及Factory,通过测试方法和Tinker运行填充数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

建表

这是一张测试用的账单表,sql语句如下:

CREATE TABLE `wallet_balance_record` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `user_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '用户ID',
  `balance` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '变更金额',
  `remark` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '余额变更备注',
  `deleted_at` timestamp NULL DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

建模型

在app/Models下新建模型WalletBalanceRecord,模型中内容如下:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class WalletBalanceRecord extends Model
{
    use SoftDeletes;

    protected $fillable = [];

    protected $table = 'wallet_balance_record';
    protected $hidden = [
        'deleted_at'
    ];
}

factory核心工作

打开database文件夹下的factories文件ModelFactory.php文件(此文件默认存在 laravel5.4, 直接在这里面进行操作),代码如下:

<?php

/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| Here you may define all of your model factories. Model factories give
| you a convenient way to create models for testing and seeding your
| database. Just tell the factory how a default model should look.
|
*/

/** @var \Illuminate\Database\Eloquent\Factory $factory */
$factory->define(App\Models\WalletBalanceRecord::class, function (Faker\Generator $faker) {
    static $password;

    return [
        'user_id' => rand(1,1000),
        'balance' => rand(0.01,99999.99),
        'remark' => 'ceshi'
    ];
});

运行

在测试方法中运行

  1. 完成路由,在api.php中添加测试路由
$api->get('test', TestController::class . '@test');
  1. 完成控制器
<?php
namespace App\Api\Controllers\Backend;

use App\Api\Controllers\BaseController;
use App\Models\WalletBalanceRecord;

class TestController extends BaseController
{
    public function test(){
        factory(WalletBalanceRecord::class)->times(30)->create();
    }
}
  1. 运行测试方法,可以看到数据库已经生成30条数据

在这里插入图片描述

使用tinker运行

在根目录命令行运行命令

php artisan tinker

进入tinker,之后再运行命令

factory(\App\Models\WalletBalanceRecord::class)->times(5)->create();

可以看到,有生成5条新的数据,如下图
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值