问题描述
我在 tinker 上使用以下命令使用工厂模型类插入一些虚拟数据: 当我跑
composer dump-autoload,PHP artisan tinker,Page::factory(10)->create()
PHP 错误:在第 1 行的 /var/www/html/laravel/laravel8-blogeval()'d
代码中找不到类“Page”
<?PHP
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Page extends Model {
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'title','slug','body','excerpt','image','thumb','view_count','user_id','Meta_keywords','Meta_description','social_image','order','published_at','is_active','is_destroy'
]; }
我的工厂文件位置 database/factories/PageFactory.PHP
<?PHP
namespace Database\Factories;
use App\Models\Page;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
class PageFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = Page::class;
/**
* Define the model's default state.
*
* @return array
*/
public function deFinition()
{
$title = $this->faker->title;
$slug = Str::slug($title);
$user = User::count() >= 20 ? User::inRandomOrder()->first()->id: User::factory();
return [
'title'=> $title,'slug' => $slug,'body' => $this->faker->text(300),'image' => $this->faker->imageUrl(900,300),'user_id' => $user,];
}
}
请问如何使用 tinker 在 Laravel 8 中插入虚拟数据?谢谢。
解决方法
我建议为您的模型使用完整路径,但是您不能直接将计数传递给工厂,您应该使用 count 方法:
App\Models\Page::factory()->count(10)->create();
,
运行这个命令:
composer dump-autoload,php artisan tinker,Page::factory(10)->create()