问题
When using the hasMany
and belongsTo
relationships in Ember-Data, does it have to specify a class, or can I specify a mixin? For instance, I have an Attachement
model that I want to link to some other models. Specifically, I want to assign Attachement
s to Project
s and Components
. Can I use a mixin on Projects
and Component
and use that mixin as the inverse like below?
App.Attachment = DS.Model.extend({
attachedTo: DS.belongsTo('canHaveAttachments', { inverse: 'attachments'});
});
App.CanHaveAttachmentsMixin = DS.Mixin.create({});
App.Project = DS.Model.extend(App.CanHaveAttachmentsMixin, {
attachments: DS.hasMany('attachment', { inverse: 'attachedTo' });
});
Is that something officially supported by Ember?
回答1:
In our project using Ember 2.4, we have few entities, Task, Assignment and Tag. Task are taggable and assignable through polymorphic associations.
This is our models structure:
// app/models/task.js
import DS from 'ember-data';
import Taggable from 'app/mixins/taggable';
import Assignable from 'app/mixins/assignable';
export default DS.Model.extend(Taggable, Assignable, {
});
// app/models/tag.js
import DS from 'ember-data';
export default DS.Model.extend({
taggable: DS.belongsTo('taggable', { polymorphic: true }),
});
// app/models/assignment.js
import DS from 'ember-data';
export default DS.Model.extend({
assignable: DS.belongsTo('assignable', { polymorphic: true }),
});
// app/mixins/taggable.js
import Ember from 'ember';
import DS from 'ember-data';
export default Ember.Mixin.create({
tag: DS.belongsTo('tag'), // you can go with hasMany here, we only have one-to-one association
});
// app/mixins/assignable.js
import Ember from 'ember';
import DS from 'ember-data';
export default Ember.Mixin.create({
assignment: DS.belongsTo('assignment'), // you can go with hasMany here, we only have one-to-one association
});
回答2:
I've spent the last day testing and researching this problem and I've finally found the answer: no. I did quite a bit of testing and couldn't get it to work. Finally, I figured out that it's because mixins (as far as I can tell) aren't in the prototype chain of an object.
To solve the problem, I just ended up using multiple relationships instead of a single polymorphic one. It's not quite as object oriented, but it's more explicit.
来源:https://stackoverflow.com/questions/21049626/polymorphic-relationship-with-mixin