Laravel 同时种子关系

Seeds relations at the sametime in Laravel

我在 laravel 中有两个具有 OneToOne 关系的模型,Team 和 Venue。 我正在尝试填充两个 table,但每个都需要 id 作为来自另一个模型的另一个 table 的外键。例如,如果我想创建一个 Venue,我需要 Team id,但它还不存在。反之亦然。

Array with the data

array:2 [▼
  "team" => array:5 [▼
    "id" => 1
    "name" => "Belgium"
    "country" => "Belgium"
    "founded" => 1895
    "national" => true
  ]
  "venue" => array:6 [▼
    "id" => 173
    "name" => "Stade Roi Baudouin"
    "address" => "Avenue de Marathon 135/2"
    "city" => "Brussel"
    "capacity" => 50093
    "surface" => "grass"
  ]
]

Migration CreateTeamsTable

Schema::create('teams', function (Blueprint $table) {
    $table->unsignedBigInteger("id")->primary();
    $table->string("name");
    $table->string("country");
    $table->integer("founded");
    $table->boolean("national");
    $table->timestamps();
});

Migration CreateVenuesTable

Schema::create('venues', function (Blueprint $table) {
    $table->unsignedBigInteger("id")->primary();
    $table->string("name");
    $table->string("address");
    $table->string("city");
    $table->integer("capacity");
    $table->string("surface");
    $table->timestamps();
});

Migration CreateTeamVenueForeign

Schema::table('teams', function (Blueprint $table) {
    $table->foreignId('venue_id')->constrained()->onDelete("Cascade");
});

Migration CreateVenueTeamForeign

Schema::table('venues', function (Blueprint $table) {
    $table->foreignId('team_id')->constrained();
});

Team Model

class Team extends Model
{
    use HasFactory;

    protected $fillable = array('id', 'name', 'country', 'founded', 'national', 'venue_id');

    public function venue()
    {
        return $this->hasOne('App\Models\Venue');
    }
}

Venue Model

class Venue extends Model
{
    use HasFactory;

    protected $fillable = array('id', 'name', 'address', 'city', 'capacity', 'surface', 'team_id');

    public function team()
    {
        return $this->hasOne('App\Models\Team');
    }
}

OneToOne 关系需要一个外键,而不是两个。如果您在两个 table 中创建外键,您将无法在不违反约束的情况下添加任何记录。

查看 Laravel 文档中的 this paragraph。 如果您的一个实体具有 hasOne() 关系,则另一个实体应该具有 belongsTo()。哪一个会有哪个取决于你把外键放在哪个 table 中。