使用Laravel模型工厂和Tinker出现问题,如何解决?

使用php artisan tinker,Job::factory()->count(10)->create();显示
Error Class "job" not found.
不知道是哪里出了问题。

我的Job.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Job extends Model
{
        protected $table = 'job_listings';

        protected $fillable = ['title', 'salary'];
}

我的JobFactory.php

<?php

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Job>
 */
class JobFactory extends Factory
{

/**
 * Define the model's default state.
 *
 * @return array<string, mixed>
 */
        public function definition(): array
        {
                return [
                        'title' => $this->faker->jobTitle(),
                        'salary' => $this->faker->numberBetween(30000, 100000),
                 ];
         }
 }
阅读 1.4k
2 个回答

Job.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory; //添加这一行

class Job extends Model
{
    use HasFactory; //启用 factory() 方法

    protected $table = 'job_listings';
    protected $fillable = ['title', 'salary'];
}

JobFactory.php

<?php

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Job>
 */
class JobFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition(): array
    {
        return [
            'title' => $this->faker->jobTitle(),
            'salary' => $this->faker->numberBetween(30000, 100000),
        ];
    }
}

使用方式

进入 Tinker:

php artisan tinker

然后执行:

App\Models\Job::factory()->count(10)->create();

补充

在 Tinker 中的使用方式

  • 如果是在 Tinker 中操作,不能使用 use 语句,但可以直接这样写:

    App\Models\Job::factory()->count(10)->create();
  • 如果是在 Seeder、Controller 或 Artisan Command 中使用,就可以这样写:

    use App\Models\Job;
    
    ...
    
    Job::factory()->count(10)->create();

1、tinker中正确使用方式

// 必须首先导入模型类
use App\Models\Job;

// 然后执行工厂操作
Job::factory()->count(10)->create();

2、验证工厂关联是否正确

// 在JobFactory.php中确认这行存在
protected $model = Job::class;
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进