我有两个表,“用户”和“俱乐部”,它们与“一对多”关系相关。这意味着每个用户可以与多个俱乐部关联,并且每个俱乐部由一个用户拥有。但是,当尝试创建新俱乐部并将其用户设置为当前用户记录时,会遇到错误:'无法读取未定义的属性'set'。'. 抛出错误的代码段:
@writer async addClub(name, location) {
const newClub = await this.collections.get('clubs').create( club => {
club.user.set(this) // <= this throws "Cannot read property 'set' of undefined"
club.name = name
club.location =location
})
return newClub
}
型号:
class User extends Model {
static table = 'users';
static associations = {
clubs: { type: 'has_many', foreignKey: 'user_id' },
}
@text('email') email;
@field('password') password;
@text('first_name') firstName;
@text('last_name') lastName;a
@text('username') username;
@readonly @date('created_at') createdAt;
@field('is_active') isActive;
@field('is_deleted') isDeleted;
@field('is_admin') isAdmin;
@field('is_onboarded') isOnboarded;
@children('clubs') clubs;
@writer async addClub(name, location) {
const newClub = await this.collections.get('clubs').create( club => {
club.user.set(this)
club.name = name
club.location =location
})
return newClub
}
}
class Club extends Model {
static table = 'clubs';
static associations = {
users: { type: 'belongs_to', key: 'user_id' },
groups: { type: 'has_many', foreignKey: 'club_id' },
}
@text('name') name;
@text('location') location;
@text('logo') logo;
@readonly @date('created_at') createdAt;
@readonly @date('updated_at') updatedAt;
@field('is_active') isActive;
@field('is_deleted') isDeleted;
@relation('users', 'user_id') user;
@children('groups') groups;
}
该项目的依赖项列表:
"react-native": "0.72.7",
"@nozbe/watermelondb": "^0.27.1",
"@babel/plugin-proposal-decorators": "^7.23.3",
"@babel/preset-env": "^7.20.0",
Babel.config.js
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: [
["module:react-native-dotenv",
{
"moduleName": "@env",
"path": ".env",
"blacklist": null,
"whitelist": null,
"safe": false,
"allowUndefined": true
}
],
["@babel/plugin-proposal-decorators", { "version": "legacy" }],
'react-native-reanimated/plugin'
],
};
_setRaw
功能。我认为,在你的代码中,它看起来像这样:
@writer async addClub(name, location) {
const newClub = await this.collections.get('clubs').create( club => {
club._setRaw('user_id', this.id); // <= This sets the raw field
club.name = name
club.location =location
})
return newClub
}
在查看文档以查看我是如何发现这一点时,我看到了对可用于设置字段的 record._raw 属性的引用。也许你不需要进行函数调用,只需执行
club._raw.user_id
即可,但我还没有测试过。