How To Query Another Table if Key Value exists in Current Model
I have a list of fire department apparatus that shows their current status. The page refreshes periodically. The query that displays the apparatus status has a field in it for an IncidentID. If an apparatus gets assigned to an incident the IncidentID that you see there is the ID of the incident found in a separate incidents table. I need to figure out how to display a few of the fields from the incident table in the existing list of incidents when that value is not null. If I set it up as a one to one, will I have any problems when that field is NULL?
You can see that M1 and M2 are currently assigned to an incident and currently display the IncidentID under the status. I want to query the incident table and get the IncidentType, and IncidentAddress and display them there instead of the IncidentID, but I am confused on how to do that in Laravel.
You’re already doing a check to see if the vehicle has a master incident ID so you should be able to safely put those in there, obviously if those properties could be null you’ll want to add some default value if necessary. Hope that helps, unless I have misunderstood what you’re asking.
@phayes0289 I'm a little confused by your naming, but I'm assuming Master_Incident_ID is the id for the CadIncident? Anyway, if so, you probably need to spell out your foreign key in your relationship as you are breaking convention. Try
public function cadIncident()
{
return $this->hasOne(CadIncident::class, 'Master_Incident_ID');
}
You should then be able to use (check the spelling though) in your blade
you should have a relationship where a vehicle has many incidents and an incident has many vehicles, and a pivot table to manage the many to many relationship.
Then use the has one of many relationship to get just the latest incident for a vehicle. It will always return one if the vehicle has previous incidents, so in the view, before showing the incident, check if the incident is 'live' before showing it as allocated
@snapey It is kind of hard to explain, but here I go. The table of vehicles basically shows their current GPS location and other meta data. When a vehicle gets assigned to a call, the incident_id field gets updated temporarily with the incident number to which it is assigned to. When the unit clears, that field gets blanked out again. So it is NOT a permanent relationship.
@Ben Taylor .. With the foreign key added via migration, it only returns the units that are actively assigned to an incident. I need all units to display, showing their current location. And only if they get assigned to an incident, I want the incident details to be displayed.