我正在爲RPG遊戲創建API(Laravel 5),並試圖播種數據。播種一對多關係
每個級別都包含很多任務,每個任務都屬於一個級別。通過Laravel docs
看,我只看到關係爲一個插入相關模型數據:一個(associate
)和多比多(sync, attach
),但沒有一個的例子:(level has many quests, but quests only have one level
)許多。
您可以在播種中看到下面我試圖隨機將多個任務關聯到關卡。我也試着attach
和sync
,但得到的錯誤
調用未定義的方法照亮\數據庫\查詢\生成器::聯想()
和
調用未定義方法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']);
}