San*_*hya 6 model factories laravel tinker laravel-8
在 Laravel 8 中,我可以使用工厂为用户生成虚拟数据,但我无法为产品生成数据。我收到以下错误:
error BadMethodCallException with message 'Call to undefined method App\Models\Product::factory()'. User_id in Product is the foreign key.
Run Code Online (Sandbox Code Playgroud)
我无法确定出了什么问题。
型号: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);
}
}
Run Code Online (Sandbox Code Playgroud)
型号: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);
}
}
Run Code Online (Sandbox Code Playgroud)
工厂: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,
];
}
}
Run Code Online (Sandbox Code Playgroud)
用户工厂.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),
];
}
}
Run Code Online (Sandbox Code Playgroud)
有人可以帮我吗?
| 归档时间: |
|
| 查看次数: |
12756 次 |
| 最近记录: |