Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best syntax to get primary key as an integer

I have been using Scala and the Play Framework for about a month now and I still haven't found a pleasant way to write SQL requests using the anorm library.

In my application I often find myself doing this sort of things:

// projectId and componentId are foreign keys. 
case class ProjectComponent(id: Pk[Int], projectId: Int, componentId: Int)

object ProjectComponent extends Magic[Event]
{
    def findForProject(project: Project) : List[ProjectComponent]
    {
        val projectId = project.id.get.get
        ProjectComponent.find("projectId=" + projectId).list()    
    }    
}

The line I am not happy with is:

// project.id returns Pk[Int]
// project.id.get returns Option[Int]
// project.id.get.get returns Int    
val projectId = project.id.get.get

Is there a better way to get the project id as an integer? Thinking about it I only need the project id to write the query. There might be a function in Play that deals with the Pk type automatically.

I am new to Scala and Play so I might have missed something obvious in the documentation.

Thanks,

Clem


1 Answers

I don't know of any way to use the Pk directly in queries, although I wouldn't be surprised if it is possible. As to retrieving the Pk value, I found the following on the Pk class:

def apply() = get.get

Thus these two calls are equivalent:

val projectId = project.id.get.get
val projectId = project.id()
like image 97
Zecrates Avatar answered Nov 22 '25 08:11

Zecrates



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!