[英]Problem with Laravel 8: Call to a member function count() on null
[英]Laravel 8 Seeder Factory : Call to a member function count() on null
当我开始使用db:seed
为我的数据库播种时,我收到了这个错误:
Call to a member function count() on null
at P:\<folderName>\<folderName>\src\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Factories\HasFactory.php:18
14▕ {
15▕ $factory = static::newFactory() ?: Factory::factoryForModel(get_called_class());
16▕
17▕ return $factory
➜ 18▕ ->count(is_numeric($parameters[0] ?? null) ? $parameters[0] : null)
19▕ ->state(is_array($parameters[0] ?? null) ? $parameters[0] : ($parameters[1] ?? []));
20▕ }
21▕
22▕ /**
1 P:\<folderName>\<folderName>\src\database\seeders\UserSeeder.php:23
App\Models\UserPhoto::factory()
2 P:\<folderName>\<folderName>\src\vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php:36
Database\Seeders\UserSeeder::run()
我尝试按照文档中的示例覆盖默认工厂,但没有帮助。
这是我的 model:
class UserPhoto extends Model
{
use HasFactory;
/**
* Create a new factory instance for the model.
*/
protected static function newFactory()
{
return UserPhotoFactory::new();
}
}
如果我删除->has(UserPhoto::factory(1))
用户表种子正常
播种机:
class UserSeeder extends Seeder
{
public function run()
{
$city = City::first();
User::factory(15)
->for($city)
->has(UserPhoto::factory(1))
->create()
;
// UserPhoto::factory();
}
}
工厂:
class UserPhotoFactory extends Factory
{
protected $model = UserPhoto::class;
public function configure()
{
$this->afterCreating(function (UserPhoto $photo) {
$height = $this->faker->numberBetween(100, 900);
$width = $this->faker->numberBetween(100, 900);
$contents = file_get_contents('www.placecage.com/c/'.$height.'/'.$width);
$path = 'users/images/'.$photo->user_id.'/'.$photo->id.'.jpg';
Storage::disk('local')->put($path, $contents);
});
}
public function definition()
{
return [
// 'created_at' => Carbon::now()
];
}
}
用户 Model:
class User extends Authenticatable
{
use HasFactory, Notifiable;
protected $hidden = [
'password',
];
public function city() {
return $this->belongsTo(City::class);
}
public function photos() {
return $this->hasMany(UserPhoto::class);
}
}
尝试检查City
Model 中 UserPhoto 的关系名称,我假设您正在使用userPhoto
所以我将它作为第二个参数传递给has(UserPhoto::factory(), 'userPhoto')
class UserSeeder extends Seeder
{
public function run()
{
$city = City::first();
User::factory(15)
->for($city)
->has(UserPhoto::factory(1), 'userPhoto')
->create()
;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.