长话短说:
我正在使用 Laravel 和 Eloquent 并尝试为数据库播种并将多个属于关系附加到一个表,但出现错误:
调用未定义的方法 Illuminate\Database\Eloquent\Relations\BelongsTo::attach()
详细解释:
我正在使用php 7.1和Laravel 6雄辩。我正在尝试为测试数据库播种。我有以下关系结构:
一个用户有多个帖子/一个帖子属于一个用户
一个类别有多个帖子/一个帖子属于一个类别
用户模型:
class User extends Model
{
protected $table = 'users';
public function posts()
{
return $this->hasMany('App\Models\Post');
}
}
品类型号:
class Category extends Model
{
protected $table = 'categories';
public function posts()
{
return $this->hasMany('App\Models\Category');
}
}
帖子模型:
class Post extends Model
{
protected $table = 'posts';
public function category()
{
return $this->belongsTo('App\Models\Category');
}
public function user()
{
return $this->belongsTo('App\Models\User');
}
}
用户工厂:
$factory->define(User::class, function (Faker $faker) {
return [
'id' => $faker->unique()->randomNumber(3),
'name' => $faker->name(),
];
});
分类工厂:
$factory->define(Category::class, function (Faker $faker) {
return [
'id' => $faker->unique()->randomNumber(3),
'name' => $faker->word(),
];
});
邮政工厂:
$factory->define(User::class, function (Faker $faker) {
return [
'id' => $faker->unique()->randomNumber(3),
'name' => $faker->realText($maxNbChars = 200, $indexSize = 2),
];
});
如果我只有用户和帖子,我知道我可以通过以下方式为数据库播种:
public function seed()
{
$users = factory(App\User::class, 10)
->create()
->each(function ($user) {
$user->posts()->createMany(factory(App\Post::class, 10)->make()->toArray());
});
}
但显然这对我来说行不通。我尝试了以下方法:
public function seed()
{
factory(User::class, 10)->create();
factory(Category::class, 10)->create();
factory(Post::class, 100)->create()->each(function ($post){
$post->user()->attach(User::all()->random(1));
$post->category()->attach(Category::all()->random(1));
});
}
但在这两种情况下,我都收到错误:
调用未定义的方法 Illuminate\Database\Eloquent\Relations\BelongsTo::attach()
慕田峪9158850