播种一对多关系
Seeding one to many relationship
我正在为 RPG 游戏创建 API (Laravel 5),并且正在尝试播种数据。
每个关卡包含很多任务,每个任务属于一个关卡。
查看 Laravel docs,我只看到 one:one (associate
) 和 many:many (sync, attach
) 插入相关模型数据的关系, 但对于 one:many (level has many quests, but quests only have one level
).
的示例则没有
您可以在下面的播种中看到我正在尝试将多个任务随机关联到关卡。我也试过 attach
和 sync
但得到错误
Call to undefined method Illuminate\Database\Query\Builder::associate()
和
Call to undefined method Illuminate\Database\Query\Builder::attach()
关卡模型:
public function quests()
{
return $this->hasMany(Quest::class);
}
任务模型:
public function levels()
{
return $this->belongsTo(Level::class);
}
水平播种机:
public function run()
{
Eloquent::unguard();
$levels = $this->createLevels();
$quests = Quest::all()->toArray();
/*
* Randomly join level id with associated quest ids
*/
foreach ($levels as $level) {
$level->quests()->associate($quests[rand(0, count($quests) - 1)]['id']);
}
使用eloquentsave()
方法。您可以找到文档 here
您可以使用 save()
方法,如@Mithredate 所述。
foreach ($levels as $level) {
$quest->levels()->save($level);
}
我正在为 RPG 游戏创建 API (Laravel 5),并且正在尝试播种数据。
每个关卡包含很多任务,每个任务属于一个关卡。
查看 Laravel docs,我只看到 one:one (associate
) 和 many:many (sync, attach
) 插入相关模型数据的关系, 但对于 one:many (level has many quests, but quests only have one level
).
您可以在下面的播种中看到我正在尝试将多个任务随机关联到关卡。我也试过 attach
和 sync
但得到错误
Call to undefined method Illuminate\Database\Query\Builder::associate()
和
Call to undefined method Illuminate\Database\Query\Builder::attach()
关卡模型:
public function quests()
{
return $this->hasMany(Quest::class);
}
任务模型:
public function levels()
{
return $this->belongsTo(Level::class);
}
水平播种机:
public function run()
{
Eloquent::unguard();
$levels = $this->createLevels();
$quests = Quest::all()->toArray();
/*
* Randomly join level id with associated quest ids
*/
foreach ($levels as $level) {
$level->quests()->associate($quests[rand(0, count($quests) - 1)]['id']);
}
使用eloquentsave()
方法。您可以找到文档 here
您可以使用 save()
方法,如@Mithredate 所述。
foreach ($levels as $level) {
$quest->levels()->save($level);
}