【问题标题】:laravel factory model not found未找到 laravel 工厂模型
【发布时间】:2017-04-11 11:20:48
【问题描述】:

我正在尝试创建一个新项目,其中包含有关 laravel 的更多信息,现在我正在使用工厂创建模型、迁移和种子,但我遇到了这个问题:

模型用户

<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Model implements Authenticatable
{

  protected $table = 'user'; //name of the table in database
  protected $primaryKey = 'Id'; //Primary Key of the table

  /**
   * Relations between tables
   */
   public function GetLoginInfo()
   {
     return $this->hasMany('App\Models\LoginInfo', 'UserId');
   }

   public function getStatus()
   {
     return $this->belongsTo('App\Models\AccountStatus');
   }

}

模型帐户状态

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class AccountStatus extends Model
{
  protected $table = 'account_status'; //name of the table in database
  protected $primaryKey = 'Id'; //primary Key of the table
  public $timestamps = false; //true if this table have timestaps
  /**
   * Relations between tables
   */
   public function GetUsers()
   {
     return $this->hasMany('App\Models\Users', 'StatusId');
   }
}

种子文件:

<?php

use Illuminate\Database\Seeder;

class UserSeeder extends Seeder
{
  /**
   * Run the database seeds.
   *
   * @return void
   */
  public function run()
  {
    factory(App\Models\User::class, 5)->create();
  }
}

工厂文件:

<?php
/** @var \Illuminate\Database\Eloquent\Factory $factory */

//Factory for Account Status table
$factory->define(App\Models\AccountStatus::class, function (Faker\Generator $faker) {
    return [
      'Description' => $faker->word,
    ];
});

//Factory for user table
$factory->define(App\Models\User::class, function (Faker\Generator $faker) {
    return [
      'Username' => $faker->unique()->userName,
      'Password' => bcrypt('test'),
      'Email' => $faker->unique()->safeEmail,
      'Name' => $faker->name,
      'StatusId' => Factory(App\Models\AccountStatus::class)->create()->id,
    ];
});

当尝试使用工匠 db 种子时:

  [Symfony\Component\Debug\Exception\FatalErrorException]
  Class 'App\Models\Model' not found

已经在尝试 composer dump-autoload ,优化,我将模型放在 App\Models 的文件夹中。

用于帐户状态的工厂种子工作,但是当我尝试为两者运行时(帐户状态然后用户)我有那个错误)有人知道为什么吗? 将所有工厂代码放在一个文件中是一种好习惯吗?

【问题讨论】:

    标签: php laravel laravel-5.3 laravel-seeding


    【解决方案1】:

    在您的 User 模型中,您正在扩展 Model 类,而您应该扩展 Authenticatable 类别名。

    所以您的 User 模型将如下所示:

    class User extends Authenticatable
    

    【讨论】:

    • 工作了,所以可验证的已经是模型了吗?另一个问题如何从其他表信息中添加外键?这不起作用:'StatusId' => Factory(App\Models\AccountStatus::class)->create()->id
    • 是的,authenticatable 是一个模型,但请记住它只是 Illuminate\Foundation\Auth\User 的别名。对于您的第二个问题,我不确定解决方案,但您可以为此回答另一个问题。
    猜你喜欢
    • 2023-02-04
    • 2021-01-04
    • 2016-09-29
    • 1970-01-01
    • 2018-05-18
    • 1970-01-01
    • 2015-11-16
    • 1970-01-01
    相关资源
    最近更新 更多