lundi 8 octobre 2018

Eloquent one-to-one relationship to same model

I have existing data to work with: I got a table that contains all sportevents called sportevents.

id ....
name ....
....

These sportevents have a pivot table that define relations to the "same" sportevent happened in the previous year and the one of next year. Bit confusing design, but here is the table called eventrelations: I try to explain with years 2018 and 2019

id ....
event1: sportevent_id of 2019 event
event2: sportevent_id or 2018 event
....

My approach would be to create a Model called Eventrelation with the following relations:

public function previous(){
    return $this->belongsTo('App\Sportevent','id','event2' );
}

public function next(){
    return $this->belongsTo('App\Sportevent','id','event1' );
}

and in my Sportevent Model I would do the following:

public function previousEvent(){
    return $this->hasOne('App\Eventrelation','event2','id' );
}

public function nextEvent(){
    return $this->hasOne('App\Eventrelation','event1','id');
}

Although this is gonna work, I don't think this is the proper way to do it. I have setup other relations with a pivot table, but this one seems to be a bit more tricky considering the existing data structure and the relationship to the same Model. Any advice would be much appreciated.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire