laravel 利用factory数据填充
建表
这是一张测试用的账单表,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'
];
});
运行
在测试方法中运行
- 完成路由,在api.php中添加测试路由
$api->get('test', TestController::class . '@test');
- 完成控制器
<?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();
}
}
- 运行测试方法,可以看到数据库已经生成30条数据
使用tinker运行
在根目录命令行运行命令
php artisan tinker
进入tinker,之后再运行命令
factory(\App\Models\WalletBalanceRecord::class)->times(5)->create();
可以看到,有生成5条新的数据,如下图