【问题标题】:Seeding one to many relationship播种一对多关系
【发布时间】:2015-12-23 21:59:44
【问题描述】:

我正在为一款 RPG 游戏创建 API (Laravel 5),并尝试播种数据。

每个关卡包含多个任务,每个任务都属于一个关卡。

查看Laravel docs,我只看到为 one:one (associate) 和 many:many (sync, attach) 插入相关模型数据的关系,但对于 one:many (@ 987654324@).

您可以在下面的播种中看到我正在尝试将多个任务随机关联到关卡。我也试过attach 和sync 但得到错误

调用未定义的方法 Illuminate\Database\Query\Builder::associate()

和

调用未定义的方法 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']);
    }

【问题讨论】:

    标签: php laravel laravel-5 seed


    【解决方案1】:

    使用雄辩的save()方法。你可以找到文档here

    【讨论】:

      【解决方案2】:

      您可以使用save() 方法,如@Mithredate 所述。

      foreach ($levels as $level) {
          $quest->levels()->save($level);
      }
      

      【讨论】:

        猜你喜欢
        • 2019-11-17
        • 2017-12-29
        • 2019-01-05
        • 2020-02-24
        • 1970-01-01
        • 2013-05-02
        • 2013-06-21
        • 2022-11-14
        • 2021-10-29
        相关资源
        最近更新 更多