🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
## laravel 的模型工厂使用 场景 laravel 8之前的都是使用的文件类型,后面laravel 8之后改为类的形式了 文档:https://learnku.com/docs/laravel/8.x/database-testing/9416 ___ **为了简化升级过程,我们发布了一个[laravel/legacy-factories](https://github.com/laravel/legacy-factories)扩展包,可以在 Laravel 8 中支持以前的模型工厂**。 安装指令 :**`composer require laravel/legacy-factories`** ___ 安装后可以使用以前的模型工厂,如果想使用新的工厂按照对应模型的目录生成对应目录的模型工厂 如果提示找不到模型工厂那么可以尝试一下重新加载 执行名称 **`composer dump-autoload`** ___ namespace Database\Factories; use App\Models\User; use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Support\Str; class UserFactory extends Factory { /** * 工厂对应模型名称 * * @var string */ protected $model = User::class; /** * 定义模型默认状态 * * @return array */ public function definition() { return [ 'name' => $this->faker->name, 'email' => $this->faker->unique()->safeEmail, 'email_verified_at' => now(), 'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password 'remember_token' => Str::random(10), 'staus' => 1 ]; } /** * 标识用户「 已暂停 」状态。 */ public function forbid() { return $this->state([ 'status' => 0 ]); } } 对应模型 其中的 `Illuminate\Database\Eloquent\Factories\HasFactory` 的用于模型工厂的使用 如果需要使用就要加上这个trait.其中值得注意这个trait中有一个方法是提供给用户使用指定工厂的 `protected static function newFactory()` ___ ~~~ <?php namespace App\Models; use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Laravel\Sanctum\HasApiTokens; class User extends Authenticatable { use HasApiTokens, HasFactory, Notifiable; /** * The attributes that are mass assignable. * * @var array<int, string> */ protected $fillable = [ 'name', 'email', 'password', ]; /** * The attributes that should be hidden for serialization. * * @var array<int, string> */ protected $hidden = [ 'password', 'remember_token', ]; /** * The attributes that should be cast. * * @var array<string, string> */ protected $casts = [ 'email_verified_at' => 'datetime', ]; /** * Create a new factory instance for the model. * * @return \Illuminate\Database\Eloquent\Factories\Factory */ protected static function newFactory() { // return UserFactory::new(); } } ~~~ ___ HasFactory 特征的 factory 方法将使用默认的约定来确定模型的正确工厂。 具体来说,该方法将在 Database \ Factories 命名空间中寻找一个工厂,该工厂的类名与模型名称匹配,并且后缀为 Factory 。 如果这些约定不适用于您的特定应用程序或工厂,则可以直接使用工厂来创建模型实例。 要使用 factory 类创建一个新的工厂实例,应在工厂上调用静态的 new 方法: ~~~ use Database\Factories\UserFactory; $users = UserFactory::new()->count(3)->make(); ~~~ 生成一个用户模型工厂 ~~~ use App\Models\User; User::factory()->carate(); // 数据会添加到数据库中 User::factory()->make(); // 不会真的生成数据 namespace Tests\Feature; use Illuminate\Foundation\Testing\TestCase as BaseTestCase; use Tests\CreatesApplication; use Illuminate\Foundation\Testing\DatabaseTransactions; abstract class TestCase extends BaseTestCase { use CreatesApplication; use DatabaseTransactions;// 不污染数据库数据 // use RefreshDatabase; } ~~~