New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Associations #124

Closed
mikermcneil opened this Issue Feb 17, 2013 · 254 comments

Comments

@mikermcneil
Copy link
Member

mikermcneil commented Feb 17, 2013

Update:

Sails v0.10.0-rc3 is now available on npm.

Upgrading to Sails v0.10 beta:

Install:
$ sudo npm install -g sails@beta -g

Docs:
beta.sailsjs.org

Also see: https://github.com/balderdashy/waterline-docs

Migration Guide for v0.9.x apps:
https://github.com/balderdashy/sails-docs/blob/master/Migration-Guide.md

We're working on improving docs in general, but we could really use your help- please feel free to submit pull requests to https://github.com/balderdashy/sails-docs. The changes go live to beta.sailsjs.org (and eventually sailsjs.org proper, when we set the latest tag on v0.10)

@mikermcneil

This comment has been minimized.

Copy link
Member Author

mikermcneil commented Mar 2, 2013

Scott: when you do embedded models for waterline, are you going to just be adding in hidden fields like that, that are arrays or lists of object ids?
4:01 PM
me: If I understand you correctly, yes
4:02 PM
as in, how will it work w/ relational dbs?
4:03 PM
Scott: even in nosql dbs...unless you are planning on duplicating the data, but then you have to make sure its always synced up

like if you have Department and User models

me: You mean the embed query helper thing in that issue?
4:04 PM
Scott: yes

me: yeah, it's only useful for linked-relationships

where you have a foreign key

so in those cases, it grabs fresh data each time you do a query
4:06 PM
Scott: I'm just looking at the issue again now, and it looks like you're planning to physically store the Group data in the User

model for NoSQL dbs

me: yeah

Scott: which is fine, but you have to update the Group in two places then
4:07 PM
me: right

you can do it the other way though

what I had planned was, if you specify a "model" or "collection", it'll use a foreign key

otherwise it'll be stored phsyically

and it can only be stored physically in a nosql adapter

otherwise it'll bitch at you
4:08 PM
but you can use the link/relational pattern even in a nosql db

Scott: And when you do an update on a Group, it will examine all the model defs, find which ones have embedded Groups, and search those models to find ones that need updating?
4:09 PM
me: in the embedded pattern?

no

only in the relation/link pattern

in the NoSQL embedded pattern, Group doesn't actually exist
4:10 PM
Scott: it's just an attribute of UseR?

me: right

you wouldn't have a Group model file

Scott: so you can query on it, but there's no Group model

got it

me: right
4:11 PM
vs. associating the "Group" key with a "group" model

which would manage the relation for you

Scott: options

got it

me: Does that make sense? I think it might. Definitely could use more eyes on all of these things.
4:12 PM
Scott: it does, and there are cases for both

ok--different topic, if you have a second

me: surr

@dcbartlett

This comment has been minimized.

Copy link
Contributor

dcbartlett commented Mar 15, 2013

Should i documentate this?

@mikermcneil

This comment has been minimized.

Copy link
Member Author

mikermcneil commented Mar 15, 2013

It would be good to explicitly mention that we're not yet supporting named
associations in the docs, that we're waiting until we're sure we have it
right, and link back here?

On Fri, Mar 15, 2013 at 6:36 AM, Dennis Bartlett
notifications@github.comwrote:

Should i documentate this?


Reply to this email directly or view it on GitHubhttps://github.com//issues/124#issuecomment-14955991
.

Mike McNeil
Founder
http://www.linkedin.com/in/mikermcneil/ http://twitter.com/mikermcneil
http://github.com/balderdashy

   C      O
  NFI    DEN
  TIA   L i
  nfo  rma
  tion in
   tended
only for t      he addressee(s).

If you are not the intended recipient, empl
oyee or agent responsible for delivery to the
intended recipient(s), please be aware that
any review, dissemination, use,distribut
ion or copying of this message and its
contents is strictly prohibited. If
you receive this email in error, ple
ase notify the sender and destroy any
paper or electronic copies immediately.

@mikermcneil

This comment has been minimized.

Copy link
Member Author

mikermcneil commented May 31, 2013

@abuckton

This comment has been minimized.

Copy link

abuckton commented Jun 8, 2013

Hi Mike,
I saw the proposal and that looks workable. What is the current status of the association/relational work ?

@anissen

This comment has been minimized.

Copy link

anissen commented Jun 11, 2013

I would be very interested in this as well. The lack of mongoose-like populate functionality is the only thing that keeps me from migrating my project(s) to Sails.

@particlebanana

This comment has been minimized.

Copy link
Contributor

particlebanana commented Jun 11, 2013

So the first step was moving the ORM out of Sails which we are finishing now with Waterline. We also knocked out some of the low hanging fruit like validations. This will be in the 0.9 release.

The next step is definitely associations. Once the 0.9 release is out we can nail down an api then add it to Waterline pretty quickly I think. We will need to update the adapters to support the new options as well.

@anissen I love the populate method too and we will have something similar for sure. We already have the query builder interface so it works out perfect.

If anyone would like to take a look at the current state or follow the project it's all happening in balderdashy/waterline now.

@arianitu

This comment has been minimized.

Copy link

arianitu commented Jul 3, 2013

Please add foreign key constraints as a requirement to this task for associations defined using SQL.

@mikermcneil

This comment has been minimized.

Copy link
Member Author

mikermcneil commented Jul 7, 2013

@abuckton To expand on what @particlebanana said, it's coming along. Waterline has validations now, as well as custom table/attribute names and lifecycle hooks. Associations is the last big feature for Sails, IMO, other than continued performance optimizations, stability and reliability updates, and more convenience blueprints (particularly around associations)

So v0.9 is looking like a release candidate for 1.0, and (fingers crossed) the last breaking change. I'm working to get it out first, with the migration guide. Then we can work associations into a subsequent 0.9.x release since it won't change the Sails API-- just extend it.

Thanks for checking in!

@tanertopal

This comment has been minimized.

Copy link

tanertopal commented Jul 25, 2013

Is there any way of speeding up the work on associations? If you give me little overview I could work on it.

@kdocki

This comment has been minimized.

Copy link

kdocki commented Jul 28, 2013

I think it would be nice to see associations like this...

User.findOne().then(function(user) {
    user.roles = user.roles() // this isn't in 'with' so if we want to include it we need to do this
    res.json(user)
});

// might return { id: 1, roles: [{ id: 1, name: 'AdminRole'}, {id: 3, name: 'UserRole' }], primaryRole: { id: 3, name: 'UserRole' } }


var User = {
  with: [ 'primaryRole' ]
  attributes : {
    primaryRoleId : { 
        type: 'integer',
        required: true
    },
    primaryRole : function() {
       return this.hasOne('Role').where({id: this.primaryRoleId})
    },
    roles : function() {
       return this.hasManyAndBelongsTo('Role')
    }
  }
}

var Roles = {
   attributes: {
      users : function() {
          return this.hasAndBelongsToMany('User')
      }
   }
}
@mikermcneil

This comment has been minimized.

Copy link
Member Author

mikermcneil commented Jul 28, 2013

@kdocki Thanks for the input-- that's similar to what we came up with!

@particlebanana, @Zolmeister, @sgress454, @ghernandez345, @irlnathan and I got together a few weeks ago and hashed out a spec for associations. Here's the latest, pasted from a note (so apologies for any typos, this is just to give you guys an early look and get your thoughts:)

It was an interesting challenge to provide a clean, uniform API for both noSQL and SQL databases, but as with the original design of Waterline, Hibernate and Mongoose provided an excellent starting place to work from. For the new parts, we tried to keep syntax consistent.

I include them below just for reference, but you'll notice that we completely did away with the belongs and has terminology in the actual usage. That's because they've always confused the hell out of me, mainly because they don't capture the true nature of the association. e.g. a Bear doesn't belongTo a Cave, he's just living there for a while!

Instead, in Waterline, you name the association yourself. You can use conventional semantics, or use your own. In the example above, I'd probably name the association cave so I could access bear.cave. But if I need to access the bear from the cave, I might name my association on the other end something like currentBear. By making your associations explicit, you're not only creating a more descriptive data model, but also making the usage of your models more intuitive. Not to mention you can effectively ignore an entire vocabulary (belongsTo, hasWhatever, yada yada) and make associations work just like any other attribute.

The downside? Since, in Node/JavaScript, we have callbacks to think of, calls to populate() have to be explicit (or risk encouraging extremely inefficient behavior). It's a trade-off, but a fact of life when working with Node.js, and if you're reading this, you're used to it. Populate is made available as a query modifier on find(), but not on instance methods. This is designed to discourage the sort of overzealous joining common in other MVC frameworks where blocking getters are used to do on-the-fly joins. I won't name any names :)

Associations In Sails

belongsTo

A belongs_to association sets up a one-to-one connection with another model, such that each instance of the declaring model "belongs to" one instance of the other model.

Definition

belongs_to :group
group : {
  model: 'Group'
}

Usage

// Finding by association
// automatically joins
User.findByGroup(groupId)

// Force a join ({})
User.find()
.populate('group')

hasOne

A has_one association also sets up a one-to-one connection with another model, but with somewhat different semantics (and consequences). This association indicates that each instance of a model contains or possesses one instance of another model.

Definition

has_one :group
group : {
  model: 'Group'
}

Usage

// Finding by association
// automatically joins
User.findByGroup(3)

// Force a join ({})
User.find()
.populate('group')

hasMany

A has_many association indicates a one-to-many connection with another model. You'll often find this association on the "other side" of a belongs_to association. This association indicates that each instance of the model has zero or more instances of another model.

Definition

has_many :role
roles: {
  collection: 'Role'
}

Usage

// Finding by association
// automatically joins
User.find()
.where({
  roles: [1,2,3]
})

// Force a join ([])
User.find()
.populate('roles')

## hasMany :through

A has_many :through association is often used to set up a many-to-many connection with another model. This association indicates that the declaring model can be matched with zero or more instances of another model by proceeding through a third model.

Definition

has_many :permission :directory
dirPermissions: {
  collection: 'Directory',
  type: 'string'
}

Usage

// Find accounts with access to this directory (2)
// (auto-populate dirPermissions)
Account.find()
.where({
  dirPermissions: [2]
})

// Force a join ([])
Account.find()
.populate('dirPermissions')

hasOne :through

A has_one :through association sets up a one-to-one connection with another model. This association indicates that the declaring model can be matched with one instance of another model by proceeding through a third model.
Describe a 1-way relationship that has other data associated with it.

Definition

has_one :wedding :person
marriedTo: {
  model: 'Person',
  atBuilding: {
    model: 'Building'
  },
  atTime: 'datetime'
}

Usage

In this example, you'll notice we've recursively described this relationship. Weddings have a building, for instance.

// Find the person married to person #2
// (auto-populate wedding information)
Person.find()
.where({
  marriedTo: [2]
})

// Force a join ([])
Person.find()
.populate('marriedTo')

hasAndBelongsToMany

hasAndBelongsToMany is a 2-way n <-> n association. This means that if A hasAndBelongsToMany B, for any given model a of A, you can access a list of B models, x, and also for any given model b of B, you can access a list of A models, y.

Definition

has_and_belongs_to_many :label
// models/Message.js
labels: { 
  collection: 'Label'
}

// models/Label.js
attachedToMessages: {
  collection: 'Label'
}

Usage

// Finding by association
// automatically joins
// (both ways)
Message.where({
  labels: [2]
})

Label.where({
  attachedToMessages: [2,53,2]
})


// Force a join ([])
// (works both ways)
Message.find()
.populate('labels')

Label.find()
.populate('attachedToMessages')

@mikermcneil mikermcneil referenced this issue Jul 28, 2013

Closed

Relationship #25

@Foxandxss

This comment has been minimized.

Copy link

Foxandxss commented Jul 29, 2013

For a first shot on associations, it has more features than many of the competence.

About having to use .populate.... Is just syntax, what is important here are the features, how you have to use it doesn't matter that much but anyway, I like the syntax 👍

@betacar

This comment has been minimized.

Copy link

betacar commented Jul 31, 2013

Is this available in the master branch? I downloaded today SailsJS v0.9.3 and I would love to use this in my current development app. :)

@ktkaushik

This comment has been minimized.

Copy link

ktkaushik commented Jul 31, 2013

@betacar I think this is still in the making.

@tanertopal

This comment has been minimized.

Copy link

tanertopal commented Aug 9, 2013

@mikermcneil
Is there any time scale when this issue will be resolved? I'd love to help. Right now I desperately need this in one my client projects. Can I somehow get involved?

@particlebanana

This comment has been minimized.

Copy link
Contributor

particlebanana commented Aug 9, 2013

@tanertopal see #712 I'll try and get the base started this weekend so we have something to work with then once it's done I'll gladly appreciate some PR's to move the process along.

@sourcec0de

This comment has been minimized.

Copy link

sourcec0de commented Aug 13, 2013

I am interested in seeing this come to life as well. Just started working on a User model that could use some associations. I would be glad to lend some help as well.

@ElHacker

This comment has been minimized.

Copy link

ElHacker commented Aug 21, 2013

Hey, I want to help with this too!

@particlebanana

This comment has been minimized.

Copy link
Contributor

particlebanana commented Aug 21, 2013

So just a quick update on this.

I have a proof of concept up on Waterline with belongs_to and has_many and a corresponding branch on sails-mysql. It's still very much proof of concept and has a lot of sequel code in Waterline I need to pull out. It was more me working out how it will work in the core ORM and ensuring the API will work out.

I sat down this past weekend to try and figure out many_to_many associations and ended up re-writing a large portion of Waterline. It's now a 2-stage model loading process that loads all the models into memory and builds up an internal schema representation that can be synced to any database. This allows us to create join tables where needed and easily map out foreign key constraints. This works good for sequel databases such as MySQL and PostgreSQL but should also allow Mongo to build up the collections and can determine when to use embedded records vs an array of Object Id's.

I'm not sure what the API will look like for embedded records in Mongo yet but we can work on that after the base is done. I'm not sure I like the idea of adding an embedded: true flag that only works on Mongo.

Hopefully I will get some time this week to flush it out and get it pushed up so I can get some feedback on it. I have the model loader and internal schema done but broke most of the core in the process.

Not sure how familiar any of you guys are with the raw Waterline API but the new loader will work something like this. If you are using Sails this will be in the ORM hook and not something you need to concern yourself with.

var Waterline = require('waterline');

module.exports = function(cb) {

  // Create a new instance of Waterline
  var waterline = new Waterline();

  // Load up each model into memory so that it can be introspected and
  // used to build up an internal schema mapping
  sails.models.forEach(function(model) {
    waterline.loadCollection(model);
  });

  // Init the models which will take the internal schema mapping and migrate the database.
  // Because we know about the relationships we can build join tables where needed and
  // map out foreign keys on belongs_to associations.
  waterline.initialize(sails.adapters, function(err, collections) {
    if(err) return cb(err);
    sails.models = collections;
    cb();
  });
}
@Tombert

This comment has been minimized.

Copy link

Tombert commented Sep 9, 2013

Has there been any progress on this? I was hoping that associations would come rather soon.

@xdissent

This comment has been minimized.

@Tombert

This comment has been minimized.

Copy link

Tombert commented Sep 9, 2013

I should rephrase; are there any updates on when this is going to be merged into master on Sails?

@vizo

This comment has been minimized.

Copy link

vizo commented Sep 19, 2013

👍

@colus001

This comment has been minimized.

Copy link

colus001 commented Sep 21, 2013

I'm also longing for the next update with swig template and association support. And sure others too.

@AlmaasAre

This comment has been minimized.

Copy link

AlmaasAre commented May 29, 2014

It uses sails 0.10.0-rc7, while i'm using rc5 locally. It also installs two dependencies of waterline: 0.9.16 and 0.10.0-rc12..

@pablomoran

This comment has been minimized.

Copy link

pablomoran commented Jun 9, 2014

Hello all, I found an issue with the associations.

If I have a Person model that has many fingers, and I try to loop through them:

for (var i in person.fingers){
     console.log(person.fingers[i]);
}

Add and Remove functions are enumerable, so even if your person has only one finger, the for loop will iterate 3 times. (One for the finger owned by the person, one for Add and another for Remove.

I did this to fix it for now:

for (var i in person.fingers){
   if (!isNaN(i) == true){
       console.log(person.fingers[i]);
   }
}

Hope this was helpful, if there is a better place for me to report these issues please let me know.

@lwansbrough

This comment has been minimized.

Copy link
Contributor

lwansbrough commented Jun 9, 2014

@pablomoran I think using .hasOwnProperty(...) is the accepted way of doing this, but good catch - that shouldn't been happening.

@GaryLCoxJr

This comment has been minimized.

Copy link

GaryLCoxJr commented Jun 9, 2014

Actually this is a known part of JavaScript which is why ECMAScript 6 is
adding the "for i of array" which will ignore items like add and remove.

On Monday, June 9, 2014, lwansbrough notifications@github.com wrote:

@pablomoran https://github.com/pablomoran I think using
.hasOwnProperty(...) is the accepted way of doing this, but good catch -
that shouldn't been happening.


Reply to this email directly or view it on GitHub
#124 (comment).

Thank you,
Gary Cox

@pablomoran

This comment has been minimized.

Copy link

pablomoran commented Jun 10, 2014

Thanks you both for the quick feedback! @lwansbrough @GaryLCoxJr

@owen26

This comment has been minimized.

Copy link

owen26 commented Jul 25, 2014

I really like the way ASP.NET Entity Framework handles associations and if sails can get some ideas from it that would be wonderful.

@lwansbrough

This comment has been minimized.

Copy link
Contributor

lwansbrough commented Jul 25, 2014

Can you elaborate @owen26?

@GaryLCoxJr

This comment has been minimized.

Copy link

GaryLCoxJr commented Jul 25, 2014

You'll have to explain that one @owen26 , I can't think of a single thing I
like about EF.

@tieubao

This comment has been minimized.

Copy link

tieubao commented Jul 30, 2014

Thank you sails team. You guys did great works!! But I'm still waiting for Many-to-Many Through Associations. Have it done yet or i'm missing something?

@mikermcneil

This comment has been minimized.

Copy link
Member Author

mikermcneil commented Aug 1, 2014

@dknell

This comment has been minimized.

Copy link

dknell commented Aug 6, 2014

@mikermcneil Are there plans to implement the query you mentioned here?

I tried the following in Sails 0.10.1 and the associated data is not included:

socket.get('/user', {
        populate: {
            pets: {
                limit: 10
            }
        }
    },
    function(err, data) {
    console.log("Data: " + JSON.stringify(data));
});
@leejt489

This comment has been minimized.

Copy link

leejt489 commented Aug 14, 2014

Hi! Loving the associations and Sails/Waterline, but I'm a little unclear on schema creation for MySQL. I built up models in Sails and connected to an empty MySQL database with migrate set to 'drop'. I lifted Sails with no problem. Opened up MySQL Workbench to check out the schema that was just created. It's there, but no foreign keys were written to the MySQL schema. Also, all columns except for the 'id' are set to allow nulls, even if I specify them as required. Is there something I am doing incorrectly, or is the designed behavior of schema creation with Waterline?

Thanks!

@lwansbrough

This comment has been minimized.

Copy link
Contributor

lwansbrough commented Aug 14, 2014

@leejt489 I don't know if foreign keys are actually enforced by Waterline to be honest.. I don't see them in my DB. Also, required doesn't mean not null - it just means it has to be set when the model is created (ie. it cannot be ambiguous.) You can use the rule notNull: true or notEmpty: true for ensuring data is entered.

@leejt489

This comment has been minimized.

Copy link

leejt489 commented Aug 14, 2014

@lwansbrough good point on the required vs notNull or notEmpty. As for foreign keys with schema creation, I suppose Waterline is managing the referential integrity, so they are not really necessary. It would be nice to enable the number of tools that do MySQL database diagramming through reverse engineering though. A tool to create ERM diagrams from Waterline would be awesome, but not holding my breath!

@lwansbrough

This comment has been minimized.

Copy link
Contributor

lwansbrough commented Aug 15, 2014

@leejt489 In Waterline's defence, it's a cross adapter ORM which means that referential integrity could not be guaranteed in any case where you're doing cross-adapter joins. I'm guessing that's why they don't bother setting up FK's through the schema definition. If you're designing for production you'd want to tighten up any auto-generated schema anyway most likely.

@particlebanana

This comment has been minimized.

Copy link
Contributor

particlebanana commented Aug 15, 2014

@leejt489 @lwansbrough hey guys this would be a great addition to the sails-mysql or sails-postgresql adapters. Right now there is a function in the mysql adapter that builds the sql to create the table and it just ignores any foreign keys (https://github.com/balderdashy/sails-mysql/blob/master/lib/sql.js#L77-L111) but it would be pretty easy to add that into there.

I'd accept a PR if you guys feel like that would make the adapter better.

@lwansbrough

This comment has been minimized.

Copy link
Contributor

lwansbrough commented Aug 15, 2014

@particlebanana In my opinion this is pretty low priority because it's trivial to add foreign keys after the fact and they aren't something that changes often.. If I develop a need for it I'll submit a PR, sure.

@leejt489

This comment has been minimized.

Copy link

leejt489 commented Aug 16, 2014

@particlebanana I took a look at this and I think it might be a little more complex, as it will require creating the tables in order of dependencies, and it seems to me that Waterline builds the collections in alphabetical order. I tried adding this code:

    //Process FK field
    if (attribute.foreignKey) {
        return attrName + ' ' + type + nullPart + ', FOREIGN KEY (' + attrName + ') REFERENCES ' + attribute.model + '(id)'; //TODO: look up the referenced model PK
    }

and I got an error on the first (alphabetical) model with foreign keys saying it couldn't add the foreign key. The error was not specific, but I'm assuming it was because the referenced column doesn't exist yet.

There may also be dependency issues with dropping the schema for migrate setting 'drop'. Another issue is to make sure that the referenced model is (or will be) defined in the same database. I think the way to do it would be to add the constraints after all models are created. Can this be isolated to the adapter? I'm still pretty new to Waterline, but it seems like adapters get called in the context of a model, so running some code after all models are created would require modifications higher up in Waterline core.

@leejt489

This comment has been minimized.

Copy link

leejt489 commented Aug 29, 2014

@lwansbrough Do you mean referential integrity cannot be guaranteed at the database level? This makes sense, but it appears that Waterline does not enforce referential integrity at the application level by default (i.e. I can create a Pet and associate it with a User with id 100 even if that User doesn't exist I would like to get an error instead). Is this correct? Is there something I can set when defining the association to enforce referential integrity, or does it need to be custom validation, say in the Create, Add, Update blueprints if I want it for all models?

Apologies if this is not the proper thread.

@lwansbrough

This comment has been minimized.

Copy link
Contributor

lwansbrough commented Aug 29, 2014

@leejt489 The Sails guys can probably give you better info than I can, but as far as I know Waterline does not support any enforcement of referential integrity - yet. For now, I'd just either do custom validation in a lifecycle callback or I'd set up foreign key constraints in my database manually. With the latter, any foreign key failures will bubble up to Waterline and you'll get the expected error afaik.

@leejt489

This comment has been minimized.

Copy link

leejt489 commented Aug 29, 2014

@particlebanana @lwansbrough I think that referential integrity would be a great feature. As mentioned, doing it at the database level has drawbacks in that the references couldn't be enforced for cross-adapter joins, so there are advantages to having it at the application level, though for performance it is probably better to do it at the database level where possible. Perhaps another validation option for enforcing referential integrity would be the way to go. That way it could be set false and database constraints could be used where possible, and it could be set true for cross adapter joins or where performance isn't an issue.

@colepanike

This comment has been minimized.

Copy link

colepanike commented Oct 27, 2014

@tieubao 's issues is still very much present. The doc's need updating on the Through associations.

@rizr

This comment has been minimized.

Copy link

rizr commented Feb 23, 2015

Hi all, how i can search in associatins?
for example
I have model User:

module.exports = {

attributes: {
    name: {
        type: 'string',
        defaultsTo: ''
    },
    roles: {
        collection: 'Roles'
}

};

Roles model
module.exports = {

attributes: {
    type: {
        type: 'string'
        enum: ['admin','user']
}

};

how i can find all user where roles == admin? GET user?where={"roles.type":"admin"} NOT WORK

@xolubi

This comment has been minimized.

Copy link

xolubi commented Feb 23, 2015

@rizr First, modify your User model to read thus

attributes: {
    name: {
        type: 'string',
        defaultsTo: ''
    },
    roles: {
        model: 'Roles'
    }
}

and run your query using this
User.find().populate('roles', {type: 'admin'})

@rathahin

This comment has been minimized.

Copy link

rathahin commented Apr 6, 2015

Hello Guys, How can I implement recursive relationship? Assume I have menu model, and menu belong to another menu as parent, and one menu has many menu as children. So I create the model like this:

module.exports = {
  tableName:'ac_menu',
  attributes: {
    id: {
      type: 'integer',
      required: false,
      primaryKey: true,
      autoIncrement: true
    },
    name:{
      type: 'string',
      required: true
    },
    content: {
      type: 'string',
      required: true
    },
    order: {
      type: 'integer'
    },
    location: {
      model:'menuLocation'
    },
    parent: {
      model: 'menu'
    },
    children: {
      collection: 'menu',
      via: 'parent'
    },
    post: {
      model: 'post'
    }
  }
};

Is that correct way?

@leejt489

This comment has been minimized.

Copy link

leejt489 commented Apr 6, 2015

At first glance that looks correct to me. Probably stack overflow is a better place to ask this.

On Apr 6, 2015, at 1:47 AM, nsratha notifications@github.com wrote:

Hello Guys, How can I implement recursive relationship? Assume I have menu model, and menu belong to another menu as parent, and one menu has many menu as children. So I create the model like this:

module.exports = {
tableName:'ac_menu',
attributes: {
id: {
type: 'integer',
required: false,
primaryKey: true,
autoIncrement: true
},
name:{
type: 'string',
required: true
},
content: {
type: 'string',
required: true
},
order: {
type: 'integer'
},
location: {
model:'menuLocation'
},
parent: {
model: 'menu'
},
children: {
collection: 'menu',
via: 'parent'
},
post: {
model: 'post'
}
}
};
Is that correct way?


Reply to this email directly or view it on GitHub.

@rathahin

This comment has been minimized.

Copy link

rathahin commented Apr 6, 2015

Sorry, I know that is not suitable to ask here. But this is really work. Thank you for awesome work!

@balderdashy balderdashy locked and limited conversation to collaborators Feb 1, 2016

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.