I'm trying build a JOIN query in Amber (using the Granite ORM) on a legacy database (with existing data & table structure), and wondering if it's possible to customize the SELECT FROM portion of the query to support a cross-table JOIN.
Here's the current table structure for a table called vehicles
:
-----------------------------------------------
| vehicleid | year | makeid | modelid |
-----------------------------------------------
| 1 | 1999 | 54 | 65 |
| 2 | 2000 | 55 | 72 |
| ... | ... | ... | ... |
-----------------------------------------------
etc.
Where makeid
and modelid
are foreign key references to makes
and models
table. In those tables are naming columns (makename
and modelname
, respectively).
I'm trying to generate a JOIN query to pull in the names:
SELECT vehicle.yearid, make.makename AS make, model.modelname AS model FROM vehicles JOIN....
(snipping out the JOIN details).
So that when the query returns I have a single Vehicle
object and can access:
Vehicle.yearid
,
Vehicle.make
, and
Vehicle.model
Is this possible using Granite?
I can get the JOIN portion of the query to generate by using raw SQL, but I can't figure out how to customize the table & column names in the SELECT portion. I've tried creating an object as so:
class Vehicle < Granite::ORM::Base
adapter pg
primary vehicleid : Int32
field yearid : Int32
field make : String
field model : String
end
But Granite is generating the following SQL:
SELECT vehicle.yearid, vehicle.make, vehicle.model FROM vehicle JOIN...
That's throwing an error because vehicle.make
and vehicle.model
don't actually exist.
what I want is this SQL:
SELECT vehicle.yearid, make.makename AS make, model.modelname AS model FROM vehicles JOIN....
Is there a way to make this work?