Skip to content

Associations

sergeych edited this page Aug 16, 2012 · 7 revisions

under construction. This page is not yet finished and may very easily contain incomplete, wrong or outdted information!

You declare an associations in the 'owner' table, like has_many: in rails (activerecord):

class Order extends prego.Table

class Person extends prego.Table
  orders = @hasMany(Order)

This setup requires that table orders have integer person_id column, usually, you declare it in migration sql somehow like:

create table orders(
   ...
   person_id integer references persons on delete cascade,

Note that Order table must be declared before creating a reference. The last line creates 2 reference functions in Order and Person respectively:

order.person (err, person) ->
   # if !error person is either null or Person instance

person.orders.all {}, (err, orders) ->
   # if not err then orders is an array of Order instances (that can be empty, of course).

To create associated object, just assign its personId field:

new Order({personId: person.id, ...}).save (err) -> # if not err, here person.orders.all will retreive non empty collection

There is no yet any automation on associated objects creation.

Details

Please note that there is no associated objects cache, every time you ask for it, it would be retreived from DB. This is made by purpose, though, as author can implement much more effective caching that universal one that would slow down all operations and cause problems with cache invalidation.

@hasMany( model, params )

model should be an prego.Table descendant, defined before creating an association. params is a optional hash of argumenrs:

  • foreignKey - default is model_id, but it could be overriden

Autogenerated methods

  • `ownerInstance.models.all params, (err, models) -> ...

params could have where conditions like { where: 'something < $1 and other != $2', values: [10, 'nonono'] }. For more complex constructions it is recommented to use model.allBySql.

Clone this wiki locally