<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-data/2.0.0/js-data.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<h1>Open up your console to see the output</h1>
</body>
</html>
(function() {
var store = new JSData.DS();
var Blog = store.defineResource({
name: 'blog',
relations: {
hasMany: {
comment: {
localField: 'comments',
foreignKey: 'commentableId',
get: function(Blog, relationDef, blog, orig) {
return store.filter('comment', {
commentableId: blog.id,
commentableType: 'blog'
});
}
}
}
}
});
var Image = store.defineResource({
name: 'image',
relations: {
hasMany: {
comment: {
localField: 'comments',
foreignKey: 'commentableId',
get: function(Image, relationDef, image, orig) {
return store.filter('comment', {
commentableId: image.id,
commentableType: 'image'
});
}
}
}
}
});
var Comment = store.defineResource({
name: 'comment',
relations: {
belongsTo: {
blog: {
localField: 'image',
localKey: 'commentableId'
},
image: {
localField: 'blog',
localKey: 'commentableId'
}
}
}
});
var image = Image.inject({
id: 1,
comments: [{
id: 1,
commentableId: 1,
commentableType: 'image'
},
{
id: 2,
commentableId: 1,
commentableType: 'image'
}
]
});
var blog = Blog.inject({
id: 1,
comments: [{
id: 3,
commentableId: 1,
commentableType: 'blog'
}, {
id: 4,
commentableId: 1,
commentableType: 'blog'
}]
});
console.log(image);
// these comments got assigned to the image correctly!
console.log(image.comments);
console.log(blog);
// these comments got assigned to the blog correctly!
console.log(blog.comments);
})();