Search code examples
sql-order-byplayframeworksiena

Is possible in siena to order by a calculated field?


I'm trying to get a query returned ordered on a filed which is calculated in Play. This is the query I'm using.

return all().order("points").fetch();

where points is defined as

public Integer points;

and is retrieve thanks to this getter

public int getPoints(){
    List<EventVote> votesP = votes.filter("isPositive", true).fetch();
    List<EventVote> votesN = votes.filter("isPositive", false).fetch();
    this.points= votesP.size()-votesN.size();
    return this.points;
}

The getter is correctly called when I do

int votes=objectWithPoints.points;

I have the feeling I'm pretending a bit too much out of siena, but I would love this to work (or some similar code). Currently it just skips the order condition. Ordering on any other field works correctly.


Solution

  • I think you're true when you say you await a bit too much :)
    The Siena query all().order("points").fetch() performs a request to the DB. So it will order the values stored into the DB not into your program.

    From what you say, I see that you have a getter getPoints which computes a value. Yet, if you don't store this value into the database, the ordering can't be performed by Siena.

    So either you compute the value, set it in your object and save the object to the DB.

    objectWithPoints.points = getPoints();
    objectWithPoints.save();
    

    Either you order values by yourself in your program after computing them.