How to add an alias to the selected field?

41 views Asked by At

I want to join two tables with the id fields. Later, I want to access those fields using row.get("field_name") method from sqlx.

As far as two fields have the same name I want to add an alias to prevent the naming collision.

Here is my code snippet

let (query, values) = Query::select()
    .columns([
        (DbWorkingDay::Table, DbWorkingDay::Id) // How to add aliasl here?
    ])
    .columns([
        (DbAppointment::Table, DbAppointment::Id), // ...and here
    ])
    .from(DbWorkingDay::Table)
    .inner_join(DbAppointment::Table)
    ...

Currently, both of those fields return as id. Expected result should be working_day_id and appointment_id.

Any idea how to add aliases?

1

There are 1 answers

0
Roman Mahotskyi On BEST ANSWER

I was able to add alias to the column names by using sea_query::query::SelectStatement::expr_as.

The working solution would look like this

let (query, values) = Query::select()
    .columns([
        (DbWorkingDay::Table, DbWorkingDay::Id)
    ])
    .columns([
        (DbAppointment::Table, DbAppointment::Id), 
    ])
+   .expr_as((DbWorkingDay::Table, DbWorkingDay::Id), Alias::new("working_day_id"))
+   .expr_as((DbAppointment::Table, DbAppointment::Id), Alias::new("appointment_id"))
    .from(DbWorkingDay::Table)
    .inner_join(DbAppointment::Table)