我是 Strapi 的新手,一般来说都是后端开发,我正在尝试了解一个非常小的东西应该如何工作。
我有一个 User 模型、一个 Profile 模型和一个 Fare 模型。
用户可以拥有个人资料,因此我创建了一个关系拥有并属于一个
。
Profile 可以有 Fare,我在 Profile 和 Fare 之间创建了相同的关系。
我在这里注意到的是:
当我在客户端登陆到个人资料部分时,我会保存它的所有属性,例如:姓名、姓氏、地址等... 添加用户 ID 后一切正常。
这里的重点是,在同一个配置文件部分中,我也有票价输入,我想做的是通过保存配置文件来保存票价,而不是为票价添加特殊的保存按钮...
有什么可以做的吗,还是我在这里做错了什么?
我正在按配置文件分离票价,以便能够更好地查找、组织和处理票价,而无需每次都查询配置文件,但通过 id ro 获得配置文件记录...
有人可以清楚地解释最佳方法以及我应该怎么做才能正确实现它?谢谢
最佳答案
表单
HTML 输入创建 nested json data 你可以建立一个表格和test the output
<form action="profiles" method="POST" accept-charset="utf-8">
<input type="text" name="name" value="MyProfileName" />
<input type="text" name="fare[name]" value="MyProfileFareName" />
</form>
解析参数
参数将从您的后端接收为
name=MyProfileName&fare[name]=MyProfileFareName
Controller 会将以上参数解析为json
{
'profile' => {
'name' => 'MyProfileName',
'fare' => {
'name' => 'MyProfileFareName',
}
}
}
Controller create
或 update
Action
Controller 应负责使用接收到的参数并更新数据库模型。 add
和 edit
方法将 model
持久化到 database
中是在 service
s 对象(不在 Controller 内部), Controller 的职责仅仅是调用这些方法。
您可以从 request
的 body
中检索 parameters
。 request
对象在 Controller 内可用 ctx.request
作为 in this example create
Action uses the .add
method from the category
services class . api docs对此没有任何解释,您应该关注 the example on github .
module.exports = {
// POST /profiles
create: async (ctx) => {
// use the fare service to add a new entry with value request.body.fare
var profile = strapi.services.profile.add(ctx.request.body)
strapi.services.fare.add(ctx.request.body.fare)
return profile
}
};
Profile
服务 add
和 edit
方法
您可以查看 github 上的示例,以更好地了解 add
和 edit
方法的逻辑。
add: async (values) => {
// Extract values related to relational data.
const relations = _.pick(values, Profile.associations.map(ast => ast.alias));
const data = _.omit(values, Profile.associations.map(ast => ast.alias));
// Create entry with no-relational data.
const entry = await Profile.create(data);
// Create relational data and return the entry.
return Profile.updateRelations({ _id: entry.id, values: relations });
},
关于javascript - 了解strapi关系如何运作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56082178/