问题描述
在 Laravel 8 中,我可以使用工厂为用户生成虚拟数据,但我无法为产品生成数据。我收到以下错误:
error BadMethodCallException with message 'Call to undefined method App\Models\Product::factory()'. User_id in Product is the foreign key.
我无法确定哪里出了问题。
型号:Product.PHP
<?PHP
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
//use HasFactory;
protected $fillable = ['title','type','firstname','surname','price','papl'];
public function user(){
return $this->belongsTo(User::class);
}
}
模型:User.PHP
<?PHP
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasFactory,Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name','email','password',];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password','remember_token',];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',];
public function products(){
return $this->hasMany(Product::class);
}
}
工厂:ProductFactory.PHP
<?PHP
namespace Database\Factories;
use App\Models\Product;
use Illuminate\Database\Eloquent\Factories\Factory;
class ProductFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = Product::class;
/**
* Define the model's default state.
*
* @return array
*/
public function deFinition()
{
return [
'user_id' => factory(User::class),'type'=> 'cd','title'=> $this->faker->sentence,'firstname'=> $this->faker->username,'surname'=> $this->faker->surname,'price'=> $this->faker->number,'papl'=> $this->faker->number,];
}
}
UserFactory.PHP
<?PHP
namespace Database\Factories;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
class UserFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = User::class;
/**
* Define the model's default state.
*
* @return array
*/
public function deFinition()
{
return [
'name' => $this->faker->name,'email' => $this->faker->unique()->safeEmail,'email_verified_at' => Now(),'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi',// password
'remember_token' => Str::random(10),];
}
}
有人可以帮我吗?