js-model icon indicating copy to clipboard operation
js-model copied to clipboard

Associations?

Open saimonmoore opened this issue 14 years ago • 8 comments

Any plans for rudimentary associations between models? How are you doing this now?

saimonmoore avatar Jul 16 '10 11:07 saimonmoore

Hi Saimon,

at the moment I declare a method on each side of the association so a Mat has many Cats:

var Cat = Model("cat", {}, {
  mat: function() {
    var mat_id = this.attr("mat_id")

    return Mat.detect(function() {
      return this.id() == mat_id
    })
  }
})

var Mat = Model("mat", {}, {
  cats: function() {
    var id = this.id()

    return Cat.select(function() {
      return this.attr("mat_id") == id
    })
  }
})

I haven't really thought about proper associations - by "proper" I suppose I mean something like ActiveRecord's declarative syntax - but it would certainly be possible to encapsulate the above logic into less code.

What kind of thing were you thinking?

benpickles avatar Jul 18 '10 20:07 benpickles

yeah I was thinking of AR-style. I also do what you're doing right now but I was wondering wether you had intentions of making it more declarative. If you haven't done it by the time I get to it, I'll give it a stab.

saimonmoore avatar Jul 19 '10 05:07 saimonmoore

Sounds good to me!

benpickles avatar Jul 19 '10 09:07 benpickles

I'm currently working on this feature. It's still in testing phase, but I'm expecting the first iteration to work like this: var Post = Model("post"); var Comment = Model("comment");

Post.hasMany(Comment);
Comment.belongsTo(Post);

var p = Post.first();
p.comment(); // return []

var c = new Comment();
c.post(); // return null

c.attr("post_id", p.id());
c.post(); // return p
p.comment(); // return c

Let me know what you think. It's kinda half-working right now, I need to test it more thoroughly.

tyok avatar Oct 14 '10 01:10 tyok

sounds good...I never managed to get time to finish off what I started but it was along these lines...

saimonmoore avatar Oct 14 '10 08:10 saimonmoore

cool, looks good. let me know when you have something to look at on github. in the meantime i've reopened the issue so i don't forget.

benpickles avatar Oct 15 '10 16:10 benpickles

I have pushed my branch:

http://github.com/tyok/js-model/tree/relationship

tyok avatar Oct 18 '10 06:10 tyok

sorry for my belated response, it looks good.

i've recently been thinking about some sort of plugin architecture™ to more easily enable this sort of thing so that you could extend js-model's functionality without having to mess around with the internals - something along the lines of sammy's use.

benpickles avatar Nov 05 '10 15:11 benpickles