我有一堆“属于”其他记录的记录。 (不同的模型,只是典型的 1-n 关系。)我如何在模型上调用 find 来查找所有没有属于关联的模型?
类似于:
App.Thing = DS.Model.extend({
other: DS.belongsTo( 'App.Other' ),
someattr: DS.attr('string')
});
App.Thing.find({ other: null });
编辑:
louiscoquio 的解决方案对我不起作用。所以我想我可以在 Controller 中进行过滤。
我尝试这样做的方法如下:
App.ThingsAsideController = Ember.ArrayController.extend({
unassigned: function() {
return this.filterProperty('other');
}.property('content.@each')
});
如果我过滤 someattr
但无法过滤关系,则效果很好。
我猜问题是:belongsTo 关联的属性名称是什么?
编辑,有效的东西:
这可行,但我对此非常不满意:
App.ThingsAsideController = Ember.ArrayController.extend({
unassigned: function() {
return this.filter(function(item, index, enumerable){
var belongsToOther = false;
var otherThings = App.OtherThing.find();
otherThings.forEach( function( otherThing ){
otherThing.get('things').forEach( function( otherThingThing ) {
if( otherThingThing.id === item.id ) {
belongsToOther = true;
}
});
});
return !belongsToOther;
});
我一直在阅读 ember-data source,但我不知道如何查询记录的所属关联。
最佳答案
您可以使用filter
可用于 DS.Model
类的方法:
var filteredThings = App.Thing.filter(function(thing) {
return thing.get('other') === null;
});
它返回一个数组,其中包含在您传递的回调中返回 true
的所有 App.Thing
。
正如文档所述:
It returns a live RecordArray that remains up to date as new records are loaded into the store or created locally.
关于javascript - Ember .js : How to find records that do NOT have a property set?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14884478/