我正在尝试使用外键在用户有很多文章的地方播种模型。 我做了两个模型,两个工厂和一个播种机。文章表作为一个user_id列。
商品模型
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
protected $fillable = [
'title',
'body',
'user_id'
];
public function user()
{
$this->belongsTo(User::class);
}
}
用户模型
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use 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',
];
public function articles()
{
$this->hasMany(Article::class);
}
}
制品厂
<?php
use Faker\Generator as Faker;
$factory->define(App\Article::class, function (Faker $faker) {
return [
'title' => $faker->text(),
'body' => $faker->text(10000),
];
});
用户工厂
<?php
use Faker\Generator as Faker;
$factory->define(App\User::class, function (Faker $faker) {
return [
'name' => $faker->name,
'email' => $faker->unique()->safeEmail,
'email_verified_at' => now(),
'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret
'remember_token' => str_random(10),
];
});
UsersTableSeeder:
<?php
use Illuminate\Database\Seeder;
use \Illuminate\Support\Facades\DB;
class UsersTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
factory(App\User::class, 500)->create()->each(function (\App\User $user) {
$user->articles()->save(factory(\App\Article::class, rand(0, 10))->make());
});
}
}
当我运行php artisan db:seed时,出现以下错误:
Seeding: UsersTableSeeder
Symfony\Component\Debug\Exception\FatalThrowableError : Call to a member function save() on null
at D:\Media\Documents\Projets\laravel.lcoletta-blog\database\seeds\UsersTableSeeder.php:16
12| */
13| public function run()
14| {
15| factory(App\User::class, 500)->create()->each(function (\App\User $user) {
> 16| $user->articles()->save(factory(\App\Article::class, rand(0, 10))->make());
17| });
18| }
19| }
20|
Exception trace:
1 UsersTableSeeder::{closure}(Object(App\User))
D:\Media\Documents\Projets\laravel.lcoletta-blog\vendor\laravel\framework\src\Illuminate\Support\Collection.php:418
2 Illuminate\Support\Collection::each(Object(Closure))
D:\Media\Documents\Projets\laravel.lcoletta-blog\database\seeds\UsersTableSeeder.php:17
Please use the argument -v to see more details.
我不知道职业是什么
答案 0 :(得分:1)
错误是我只是忘记向模型用户和商品函数添加返回值。