I have these tables in my database, namely "airport" and "route", the id of "airport" is a foreign key in "route" (i.e. Origin, Destination).
Airport
+-------+-------------+-----------------------+
| id | airportcode | Location |
+-------+-------------+-----------------------+
| 1 | CEB | Cebu |
| 2 | MAN | Manila |
+-------+-------------+-----------------------+
Routes
+-------+-------------+-----------------------+
| id | Origin | Destination |
+-------+-------------+-----------------------+
| 1 | 1 | 2 |
| 2 | 2 | 1 |
+-------+-------------+-----------------------+
So far, this is my query in my Controller and it's only returning the "Origin, Destination"
DB::table('airport')
->join('route', 'airport.id','=','route.Origin')
->join('route', 'airport.id','=','route.Destination')
->select('route.Origin', 'route.Destination')
->get();
What I would like to do is this:
SELECT 'airport.Location' from airport, route WHERE 'route.Origin' = 'airport.id' AND 'route.Destination' = 'airport.id"
.
Any suggestions will do!
So - you want to pull out the model for a specific airport id but only if it goes to the specified destination?
Your first query will only return the two columns as that's what you told it to return
You can get the airport easily by:
Airport::find($id);
Where $id is the id from a user input for example and should be the key. Find will return a collection
You could also do:
Airport::where('id','=', $id)->first() //will return the first record - you could also use ->get() to return a collection
Then if you have a join in your Airport model such as ->hasMany you could then do:
Airport::where('id','=', $id)
->with('routes')
->get()
Which will return the airport with the related routes model attached to it
You can then take that a stage further and query the relationship by:
Airport::find($id)->routes()->where('destination','=',$dest_id);
I think that should do the trick - as long as you create the relationship correctly in the models
If you are using a select query make sure that you have mentioned all the fields you want...
it's only returning the "Origin, Destination"
because you have mentioned only those two in your select query.
try something like...
DB::table('route')
->select('route.Origin', 'route.Destination','airport.Location')
->leftjoin('airport', function($join)
{
$join->where('airport.id',array('route.Origin','route.Destination'));
// I haven't used it, if any errors pls comment
})
->get();
hope this helps you...