【问题标题】:filtering backbone collection on return 1 results在返回 1 结果时过滤主干集合
【发布时间】:2014-11-26 16:14:15
【问题描述】:

我正在尝试过滤骨干集合以仅返回与几个属性匹配的模型,我只想返回 owner_id 为 null 且 user_id 等于“1”的模型。这是我的代码,

myFilter: function( owner_id, user_id) {
    console.log(owner_id, user_id);
    var filtered = this.filter(function(user) {
        return user.get("owner_id") === owner_id && user.get("user_id") === user_id});
    return new App.Collections.MyClients(filtered);
}

我知道我的收藏中有 2 条匹配的记录,但我只返回了第一个,这是为什么呢?

采集数据是这样的,

id  name        information     type     user_id    owner_id
18  Client 1                    client       1         NULL
19  Client 2                    client       1         32
20  Client 3                    client       1         NULL

user_id 作为字符串返回

【问题讨论】:

  • 你能发布收集数据吗?
  • 查看编辑。我有数据库行的样子
  • 您可以尝试将严格相等运算符 (===) 更改为普通相等运算符 (==) 吗?我认为当您在代码中使用 owner_id 列中的 NULL 值时,它可能不是正确的类型。
  • 那随机返回没有结果,我想知道是不是因为我将 null 作为 myFilter 函数的第一个参数发送?
  • 好的,所以我编码的 owner_id 应该为 null 并将其从参数中取出,现在我得到模型返回,但只有第一个匹配的模型

标签: javascript backbone.js backbone.js-collections


【解决方案1】:

通过查看您发布的集合数据,最明显的答案似乎是您的MyClient 模型具有idAttributeuser_id

主干集合不能包含重复的模型,在这种情况下重复意味着具有相同 idAttribute 的模型。

假设user_id 中的idAttribute,当您调用时:

return new App.Collections.MyClients(filtered);

您的MyClients 集合将只包含第一个user_id 为1 的模型,尽管您的filtered 对象包含多个user_id 为1 的模型。

来自主干注释源代码中的set方法:

// If a duplicate is found, prevent it from being added and optionally merge it into the existing model.
if (existing = this.get(id)) {
  if (remove) modelMap[existing.cid] = true;
    if (merge) {
      attrs = attrs === model ? model.attributes : attrs;
      if (options.parse) attrs = existing.parse(attrs, options);
      existing.set(attrs, options);
      if (sortable && !sort && existing.hasChanged(sortAttr)) sort = true;
    }
    models[i] = existing;
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-18
    • 1970-01-01
    • 2020-09-05
    • 2017-01-05
    • 1970-01-01
    • 2016-12-21
    相关资源
    最近更新 更多