我在 database->factories 目录中有这个 PostFactory.php 文件:
<?php
namespace Database\Factories;
use App\Models\Post;
use Illuminate\Database\Eloquent\Factories\Factory;
class PostFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = Post::class;
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
return [
'user_id' => User::factory(),
'title' => $this->faker->sentence,
'message' => $this->faker->paragraph
];
}
}
Run Code Online (Sandbox Code Playgroud)
现在,当我运行此命令时
Post::factory()->create();
Run Code Online (Sandbox Code Playgroud)
来自修补匠
我收到了那个错误信息
找不到“数据库/工厂/用户”类
:(有什么我遗漏的吗?
您需要导入用户模型。对于 Laravel 8,你的PostFactory.php文件应该是这样的;
<?php
namespace Database\Factories;
use App\Models\User;
use App\Models\Post;
use Illuminate\Database\Eloquent\Factories\Factory;
class PostFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = Post::class;
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
return [
'user_id' => User::factory(),
'title' => $this->faker->sentence,
'message' => $this->faker->paragraph
];
}
}
Run Code Online (Sandbox Code Playgroud)
查看有关编写工厂的 laravel 文档以获取更多信息。
至于prnt上的错误(在评论中发现),您需要提供更多信息。
但是,开始时请考虑检查您的数据库:
如果是这种情况,请考虑删除它或使用 tinker 手动分配外键(即将帖子与用户关联),然后再次尝试创建工厂。当您尝试将必需的列强制用于尚未拥有它的现有数据时。
| 归档时间: |
|
| 查看次数: |
3722 次 |
| 最近记录: |