【发布时间】:2021-02-02 09:31:51
【问题描述】:
我目前正在关注 laracasts 从头开始的 laravel 系列,但由于该系列的 laravel 版本是 laravel 6,因此我陷入了这个问题。我已经在这里搜索了答案并找到了类似的线程,但我的情况不同,因为我安装了新的 laravel 8 版本。
我正在使用 tinker 上的这个命令使用工厂模型类创建一个虚拟数据:
Article::factory()->count(1)->make();
这是我得到的错误:
PHP Fatal error: Class 'Article' not found in Psy Shell code on line 1
这是我的模型 Article.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
use HasFactory;
protected $guarded = [];
}
这是我的工厂 ArticleFactory.php
<?php
namespace Database\Factories;
use App\Models\Article;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
class ArticleFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = Article::class;
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
return [
'user_id' => User::factory(),
'title' => $this->faker->sentence,
'excerpt' => $this->faker->sentence,
'body' => $this->faker->paragraph
];
}
}
我尝试使用用户的默认模型和工厂创建一个虚拟数据,它工作得很好。我在 tinker 上使用了相同的代码:
>>> User::factory()->count(1)->make();
[!] Aliasing 'User' to 'App\Models\User' for this Tinker session.
=> Illuminate\Database\Eloquent\Collection {#3289
all: [
App\Models\User {#3294
name: "Lane Maggio I",
email: "tromp.deion@example.com",
email_verified_at: "2020-10-19 15:08:24",
},
],
}
【问题讨论】:
-
你在创建模型/工厂后是否运行
composer dump-autoload?有时,tinker(和其他控制台命令)中缺少类定义,直到该命令运行为止。 -
是的,我将 make() 更改为 create() 以便将其保存在数据库中。