长话短说,我的 Larvel 8 (Jetstream) 应用程序中有一个名为 Board 的模型。我正在尝试为这个 Board 模型生成一个工厂。
当我使用以下任一命令时:
php artisan make:factory BoardFactory
或
php artisan make:factory BoardFactory --model=Board
我生成了一个看起来没有错误或问题的工厂类。但是,当我打开该类时,它包含与模型无关的内容。
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
class BoardFactory extends Factory{
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
return [
//
];
}
}
我已经对我的应用程序中的所有模型进行了尝试,并且这种情况仍然存在。再次没有错误说找不到模型。该命令看似成功运行,但显然没有为模型生成工厂。
我知道如果需要我可以轻松地手动编写此代码,但我想了解为什么这不起作用以及我如何修复它。我越快完成测试...越好 :)
在此先感谢您的帮助。
最佳答案
尝试发布您的 Laravel stub 并确认 stub 文件内容按预期定义。
- 发布 stub 。
php artisan stub:publish
- 这应该在根项目目录中创建一个 /stubs 文件夹。
- 在该文件夹中,您将看到所有 stub 。
- 最具体地说,打开名为
factory.stub
的 stub 文件>
- 它的文件内容应该类似于这样:
<?php
namespace {{ factoryNamespace }};
use Illuminate\Database\Eloquent\Factories\Factory;
use {{ namespacedModel }};
class {{ factory }}Factory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = {{ model }}::class;
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
return [
//
];
}
}
注意事项:
从外观上看,您当前的工厂 stub 似乎缺少以下部分:
// ...
use {{ namespacedModel }};
// ...
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = {{ model }}::class;
// ...
理想情况下,在正常(默认)情况下,运行生成具有链接模型的工厂的命令应该如下所示:
命令:
php artisan make:factory BoardFactory --model=Board
预期输出文件(database/factories/BoardFactory.php):
<?php
namespace Database\Factories;
use App\Models\Board;
use Illuminate\Database\Eloquent\Factories\Factory;
class BoardFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = Board::class;
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
return [
//
];
}
}
附录:
正如 @miken32 的评论中指出的那样,在 2021 年 10 月 22 日之后发布的 Laravel 版本中,不再需要在工厂类中声明模型属性:
At this time, database factories have this hidden feature where database models can be "guessed".
So, this pull request proposes that remove
protected $model
from the Factorystub
, as probably the current "guess" logic works for99.99%
of the people. In addition, I've also pull requested to the skeleton that we removeprotected $model = User::class
from theUserFactory.php
: laravel/laravel#5713.
关于php - 为什么php artisan make :factory not Generating with a Model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70310252/