Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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');
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
267 views
Welcome To Ask or Share your Answers For Others

1 Answer

OneToOne relation requires one foreign key, not two. If you create foreign keys in both tables, you won't be able to add any record without constraint violation.

Take a look at this paragraph in Laravel documentation. If one of your entities has hasOne() relation, the other one should have belongsTo(). Which one will have which depends on which table you put the foreign key in.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...