Laravel如何在两个种子之间建立关系

时间:2019-10-10 09:17:13

标签: php laravel laravel-seeding

在我的laravel应用中,数据库中有两个表:

- education_categories
- educations

现在,我想创建两个Seeder,并在两者之间建立联系。

EducationCategory Seeder:

public function run()
{
    DB::table('education_categories')->insert([
        'title' => "IT"
    ]);

    DB::table('education_categories')->insert([
        'title' => "Nature and science"
    ]);

    DB::table('education_categories')->insert([
        'title' => "Science"
    ]);

    DB::table('education_categories')->insert([
        'title' => "Construction"
    ]);

    ...etc
}

现在,我想要一个教育播种机,该播种机与“教育类别播种机”有某种关系。像这样:

DB::table('educations')->insert([
    'title' => "Programmer",
    'education_categories_id' => 1
]);

这是正确的吗?我必须在我的education_categories模型中创建hasMany关系吗?

1 个答案:

答案 0 :(得分:0)

在CLI中使用php artisan make:model ModelName命令创建两个不同的模型,并创建如下关系:

class TestRelationship extends Model {

public function testrelation()
  {
    return $this->hasMany('path\TestBelongs');
  }
}



  class TestBelongs extends Model {

    public function belongsme()
    {
      return $this->belongsTo('path\TestRelationship');
    }

  }