Skip to content
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

hasMany on same table #58

Closed
czkody opened this issue Mar 3, 2013 · 4 comments
Closed

hasMany on same table #58

czkody opened this issue Mar 3, 2013 · 4 comments

Comments

@czkody
Copy link

czkody commented Mar 3, 2013

Trying to solve tree heirarchy through orm.

CREATE TABLE `category` (
  `id` int(11) NOT NULL,
  `name` varchar(1024) COLLATE utf8_czech_ci NOT NULL,
  PRIMARY KEY (`id`)
);

CREATE TABLE `category_tree` (
  `predecessor_id` int(11) NOT NULL,
  `successor_id` int(11) NOT NULL,
  `distance` int(11) NOT NULL,
  PRIMARY KEY (`predecessor_id`,`successor_id`),
  KEY `FK_category_tree_successor` (`successor_id`),
  CONSTRAINT `FK_category_tree_predecessor` FOREIGN KEY (`predecessor_id`) REFERENCES `category` (`id`),
  CONSTRAINT `FK_category_tree_successor` FOREIGN KEY (`successor_id`) REFERENCES `category` (`id`)
);

Defined model

var db = config.db;
var Category = db.define('category', {
    //properties
    id : Number,
    name : String
},{
    //options
}); 

Category.hasMany("successors", {distance : Number}, Category, {reverse: 'predecessors', mergeTable: 'category_tree', mergeId: 'predecessor_id', mergeAssocId: 'successor_id'});

Executing this:

Category(6).getSuccessors({distance: 1}, ['name', 'A'], function(err, categories) {
    res.json(categories);
});     

generates:

SELECT * FROM `category` WHERE `distance` = 1 AND `category_tree`.`predecessor_id` = 6 ORDER BY `name` ASC 
@dresende
Copy link
Owner

dresende commented Mar 4, 2013

Thank you for your example, I'll test and debug as soon as I have time.

@dresende
Copy link
Owner

dresende commented Mar 4, 2013

The problem is your ordering (['name', 'A']). If you remove this argument it works. I'm going to see if it's possible to add ordering to the method.

@czkody
Copy link
Author

czkody commented Mar 4, 2013

You're right, I didn't try. It works fine without ordering, but with ordering it would be better. :) Thank you, you are doing great work.

@dresende
Copy link
Owner

dresende commented Mar 4, 2013

Thank you. You can try it now :)

@dresende dresende closed this as completed Mar 4, 2013
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants