leafo / lapis

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

Support passing a model instance instead of a string in relations #752

Closed JDaance closed 1 year ago

JDaance commented 2 years ago

image

"Users" here have to be a string, that will be required like this

image

I would like to be able to pass a model instance like this instead when needed:

image

leafo commented 2 years ago

So the reason why it exists the way it currently does it to avoid issues with circular dependencies. You may not have access to the value of the model yet. (eg. they both have a relation to each other)

Maybe an alternative general purpose solution is to allow using a function in place of the string to lazily load the value of the model instance.

As a work around for you current problem of not wanting to use the forced method of organizing models, you can use package.loaded

package.loaded.models = {
  userTable = self._userTable, -- ..etc
}

Then reference the model as "userTable" in the class declaration.

JDaance commented 2 years ago

Yes I suspected that it might be due to circular deps!

I would be fine with a function based approach, but I would like even better if it accepted string (current), instance (to use when no circular deps are present) and function. But I can see that the circular situation is very common, declaring the relationship on both sides.

I did a workaround by passing a string as it wants and then override get_relation_model on that specific model (matching on the string).