leafo / lapis

A web framework for Lua and OpenResty written in MoonScript
http://leafo.net/lapis/
MIT License
3.14k stars 247 forks source link

table relation with primary keys and foreign keys #736

Closed ghost closed 1 year ago

ghost commented 3 years ago

Although most of the information provided in the lapis documentation is to operate on a single table, how can I make filters or projections by relaunching tables, for example with the following statement?

SELECT u.id,u.activated,v.expire AS token_expire FROM users AS u INNER JOIN verifications AS v ON u.id = v.id;

a quick way is to usequery (query, params ...) but is there another method?

ghost commented 3 years ago

this is my temporal solution

local userModel = {
    users = require("lapis.db.model").Model:extend("users"),
    db    = require("lapis.db")
}

function userModel:findUser(username,email)
    local str_query = "SELECT u.id,u.activated,v.expire AS token_expiration FROM users AS u "..
                          "INNER JOIN verifications AS v ON u.id = v.id "..
                          "WHERE u.username = ? OR u.email = ? LIMIT 2"

    local list_users = self.db.query(str_query,username,email)

    return list_users
end

return setmetatable({}, { __index = userModel })
leafo commented 1 year ago

For the time being, lapis will not support using join syntax for preloading relations. You are still welcome to use joins by writing the sql fragments yourself.