I have two models in laravel with a OneToOne relation, Team and Venue. I'm trying to populate both tables, but each one needs the id as a foreign key of the other table from another model. For example, if I want to create a Venue, I need the Team id, but it doesn't exist yet. And vice versa.
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('AppModelsVenue');
}
}
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('AppModelsTeam');
}
}