gpt4 book ai didi

javascript - 用对象填充的外键

转载 作者:数据小太阳 更新时间:2023-10-29 03:55:14 25 4
gpt4 key购买 nike

我想使用 Backbone 关系在两个模型用户和任务之间建立关系。

两个模型之间的关系如下:

taskModel.creator_id = userModel.id   

// TaskModel
var TaskModel = Backbone.RelationalModel.extend({

relations: [
{
type: Backbone.HasOne,
key: 'creator',
keySource: 'creator_id',
relatedModel: Users
}
],

// some code
});

// Task collection
var TaskCollection = Backbone.Collection.extend({

model: TaskModel,

// some code

});

// User Model
var User = Backbone.RelationalModel.extend({
// some code
});

其实问题出在collection.models,请看附件:

请检查这个 jsfiddle:http://jsfiddle.net/2bsE9/5/

var user = new User(),
task = new Task(),
tasks = new Tasks();

task.fetch();
user.fetch();
tasks.fetch();

console.log(user.attributes, task.attributes, tasks.models);

enter image description here

附言:

实际上我正在使用 requireJs 来获取 UserModel,所以我不能在 relatedModel 值中包含引号。

define([
'models/user',
'backbone',
'relationalModel'
], function (User) {
"use strict";

var Task = Backbone.RelationalModel.extend({
relations: [
{
type: Backbone.HasOne,
key: 'creator',
keySource: 'creator_id',
relatedModel: User
}
],
});
);

最佳答案

编辑 2:

http://jsfiddle.net/2bsE9/13/

我更新了 jsfiddle 以反射(reflect)我在下面建议的更改。只要您在任务中调用 toJSON,到达服务器的就是一个 json 对象,其 creator_id 属性设置为用户的实际 id。此处的 keyDestination 是多余的,因为文档指出如果您使用 keySource,它会自动设置。

编辑:

https://github.com/PaulUithol/Backbone-relational#keysource

https://github.com/PaulUithol/Backbone-relational#keydestination

https://github.com/PaulUithol/Backbone-relational#includeinjson

以上三者的组合可能会解决您的问题。

var Task = Backbone.RelationalModel.extend({
relations: [
{
type: Backbone.HasOne,
// The User object can be accessed under the property 'creator'
key: 'creator',
// The User object will be fetched using the value supplied under the property 'creator_id'
keySource: 'creator_id',
// The User object will be serialized to the property 'creator_id'
keyDestination: 'creator_id',
// Only the '_id' property of the User object will be serialized
includeInJSON: Backbone.Model.prototype.idAttribute,


relatedModel: User
}
],
});

文档还指出,您的代码不应使用 keySourcekeyDestination 指定的属性。该属性不能作为属性访问。

如果解决了您的问题,请尝试并发表评论。

顺便说一句,这是一篇很好的博客文章,它使用端到端的 Backbone 关系。 http://antoviaque.org/docs/tutorials/backbone-relational-tutorial/

关于javascript - 用对象填充的外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11346777/

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