I have a table of flights. Each flight has a field to set the flight after. There will be a start/end of the chain eg. you cannot set the next flight to one that is already in the chain. I have set up the relationships in a laravel model to be a hasOne (linked_flight_after) and a belongsTo (linked_flight_before).
The flight after/before can successfully be retrieved, however if i wanted to retrieve all flights before/after the only way I think of doing it is in a loop going through each one-by-one.
I have tired this so far:
$flightsBefore = [];
$flightBefore = $flight->linked_schedule_before;
while ($flightBefore) {
array_unshift($flightsBefore, $flightBefore);
$flightBefore = $flightBefore->linked_schedule_before;
}
This works but if you have a long chain this would run a lot of queries to retrieve them all, is there a more efficient way of doing this?
2
Answers
There must be a common field for all the flight in your chain. For example, one might add root flight’s id (first flight in the chain) into the Flight model. And then for each flight added to the chain should share this information. With this information all flights in the hanin could be get with one query.
Use a pivot table. flight_id, chain_id, created_at (primary first 2 columns).
when a flight takes off, delete (or soft delete) the pivot for it. use order by created at desc when displaying all flights from a chain.