gpt4 book ai didi

php - 如何设置Backbone Model.idAttribute?

转载 作者:可可西里 更新时间:2023-11-01 09:57:08 24 4
gpt4 key购买 nike

我正在使用带有主干的 MongoDb/Lithium php 框架。

我希望我所有的模型 ID 和 idAttribute(s) 与我的数据库文档 ID 相同(即“_id”/mongoid)

问题:

  1. 当我打印 model.idAttribute 的值时,它仅显示为 _id。
  2. 当我打印 model.get('idAttriubte') 时,它是未定义的。
  3. 如何确保将 idAttribute 设置为与数据库 id/mongoid 相同?

这是模型类:

window.app.IHoliday = Backbone.Model.extend({
urlRoot: HOLIDAY_URL,
idAttribute: '_id',
id: '_id',
// Default attributes for the holiday.
defaults: {
},

initialize: function(props) {
},
});

这是 View 代码,在模型上调用 fetch。文档的 mongoid 作为隐藏输入 (holiday_id) 传递到此页面。

console.log('Holiday URL:' + HOLIDAY_URL );
var Holiday = new window.app.IHoliday({ _id: holiday_id });
console.log('HOLIDAY before fetch: \n' + JSON.stringify(Holiday));
Holiday.fetch(
{
success: function(){
//alert('Holiday fetched:' + JSON.stringify(Holiday));
console.log('HOLIDAY Fetched: \n' + JSON.stringify(Holiday));
console.log('Holiday name:' + Holiday.get('holiday_name'));
console.log('Holiday id:' + Holiday.id);
console.log('Holiday idAttribute:' + Holiday.idAttribute);
console.log('Holiday idAttribute:' + Holiday.get('idAttribute'));
}
});

Firebug 控制台的输出:

HOLIDAY before fetch:{"_id":"50bcaab24fbe3dfc1700000b"}
GET http://localhost:8080/li3/holidays/load/50bcaab24fbe3dfc1700000b 200 OK

HOLIDAY Fetched:
{"_id":"50bcaab24fbe3dfc1700000b","holiday_name":"eeeeeeeeeeeeeeeee","description":"","star_rating":"3","holiday_type":"family","rooms":"1","adults":"2","child":"0","emails":""}

Holiday name:eeeeeeeeeeeeeeeee
Holiday id:50bcaab24fbe3dfc1700000b
Holiday idAttribute:_id
Holiday idAttribute:undefined

编辑:以下工作......在模型类中注释掉 id 条目之后:

    window.app.IHoliday = Backbone.Model.extend({
urlRoot: HOLIDAY_URL,
//id: '_id',
idAttribute: '_id',
// Default attributes for the holiday.
defaults: {
},

initialize: function(props) {
},

最佳答案

来自主干 docs :

If you're directly communicating with a backend (CouchDB, MongoDB) that uses a different unique key, you may set a Model's idAttribute to transparently map from that key to id.

所以 idAttribute 只是告诉您的模型类,任何与 idAttribute 的值具有相同键的属性也应该复制到 id。在主干source ,这是按如下方式完成的:

if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];

基本上,如果您尝试设置与 idaAttribute 同名的属性,该值也会复制到 id

所以回答你的问题:idAttribute 不存储 id,但它存储包含 id 的属性的名称

关于php - 如何设置Backbone Model.idAttribute?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13684607/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com