如何在用户集合中更新组件Strapi v4

huangapple go评论105阅读模式
英文:

How to update component in user collection Strapi v4

问题

以下是您要翻译的内容:

[details="系统信息"]
- **Strapi 版本**: 4.5.5
- **操作系统**: Windows
- **数据库**: MySQL
- **Node 版本**: 14.20
- **NPM 版本**: 8.18.0
- **Yarn 版本**: 1.22.19
[/details]

嗨,我正在尝试更新我的用户集合中名为“billingAddress”的组件。我已经设置了一个路由,以便用户能够根据这个视频更新他们自己的数据: [在 Strapi 中更新自己的用户信息 - YouTube](https://www.youtube.com/watch?v=2ZwiiY6tnmw)

我能够更新用户数据,但一旦我需要更新组件中的数据,我就无法更新任何数据。

这是我的 Strapi 后端上扩展的样子:

module.exports = (plugin) => {
plugin.controllers.user.updateMe = async (ctx) => {
if (!ctx.state.user || !ctx.state.user.id) {
return ctx.response.status = 401;
}
await strapi.query('plugin::users-permissions.user').update({
where: { id: ctx.state.user.id },
data: ctx.request.body,
}).then((res) => {
ctx.response.status = 200;
})
}

plugin.routes['content-api'].routes.push(
    {
        method: "PUT",
        path: "/user/me",
        handler: "user.updateMe",
        config: {
            prefix: "",
            policies: []
        }
    }
)

return plugin;

}

这是我从前端使用的 Axios put 请求来更新用户数据的方式:

const handleUpdateBillingAddress = () => {
axios.put('http://localhost:1337/api/user/me', {
billingAddress: {
zipCode: "2840",
id: 1,
firstName: "Tim",
lastName: "Kerrem",
company: "mycompany",
address1: "mystreet 42",
address2: null,
city: null,
country: "Belgium",
provinceOrState: null,
zipCode: null,
phone: "+31412412412",
email: null
}
},

    {
        headers: {
            'authorization': `Bearer ${jwt}`,
            'Content-Type': 'application/json'
        },
        },
    )
    .then(response => {     
        console.log(response)
        notification.open({
            type: 'success',
            message: '成功!',
            description:'您的用户信息已更新',
            });
        })
    .catch(error => {
        console.log(error);
        console.log('发生错误:', error.response);
        notification.open({
            type: 'error',
            message: '出错了',
            description:'您的一些凭据无效',
            });
    });
}

如果有人能够告诉我如何更新组件,将会非常有帮助。
英文:

[details="System Information"]

  • Strapi Version: 4.5.5
  • Operating System: Windows
  • Database: MySQL
  • Node Version: 14.20
  • NPM Version: 8.18.0
  • Yarn Version: 1.22.19
    [/details]

Hi there, I'm trying to updata a component called "billingAddress" within my user collection. I have set up a route to be able to enable a user to update their own data based on this video: Updating Your Own User Info in Strapi - YouTube

I'm able to update user data but once I need to update data in the component I'm not able to update any data.

This is what my extension looks like on the strapi backend:

module.exports = (plugin) => {
    plugin.controllers.user.updateMe = async (ctx) => {
        if (!ctx.state.user || !ctx.state.user.id) {
            return ctx.response.status = 401;
        }
        await strapi.query('plugin::users-permissions.user').update({
            where: { id: ctx.state.user.id },
            data: ctx.request.body,
        }).then((res) => {
            ctx.response.status = 200;
        })
    }

    plugin.routes['content-api'].routes.push(
        {
            method: "PUT",
            path: "/user/me",
            handler: "user.updateMe",
            config: {
                prefix: "",
                policies: []
            }
        }
    )

    return plugin;
}

This is the Axios put request I'm using to update the user data from the frontend:

const handleUpdateBillingAddress = () => {
        axios.put('http://localhost:1337/api/user/me', {
            billingAddress: {
                zipCode: "2840",
                id: 1,
                firstName: "Tim",
                lastName: "kerrem",
                company: "mycompany",
                address1: "mystreet 42",
                address2: null,
                city: null,
                country: "Belgium",
                provinceOrState: null,
                zipCode: null,
                phone: "+31412412412",
                email: null
            }
        },

        {
            headers: {
                'authorization': `Bearer ${jwt}`,
                'Content-Type': 'application/json'
            },
            },
        )
        .then(response => {     
            console.log(response)
            notification.open({
                type: 'success',
                message: 'Success!',
                description:'Your user information has been updated',
                });
            })
        .catch(error => {
            console.log(error);
            console.log('An error occurred:', error.response);
            notification.open({
                type: 'error',
                message: 'Something went wrong',
                description:'Some of your credentials are not valid',
                });
        });
    }

Would be really helpful if someone could advise me on how to update the component

答案1

得分: 2

你想尝试通过entityService进行操作,Strapi文档中提到:

Entity Service API 是与应用程序数据库交互的推荐API。Entity Service 是处理 Strapi 的复杂数据结构,如组件和动态区域的层,而较低级别的层不知道这些。

参考链接

所以尝试:

await strapi.entityService.update('plugin::users-permissions.user', ctx.state.user.id, {data: ctx.request.body })
英文:

Hi you wanna try doing this via entityService strapi doc's states:

>The Entity Service API is the recommended API to interact with your application's database. The Entity Service is the layer that handles Strapi's complex data structures like components and dynamic zones, which the lower-level layers are not aware of.

reference

so try:

await strapi.entityService.update('plugin::users-permissions.user', ctx.state.user.id, {data: ctx.request.body })

答案2

得分: 0

通过使用entityService并对数据和填充参数进行一些调整,我能够使用以下代码使其正常工作:

module.exports = (plugin) => {
    plugin.controllers.user.updateMe = async (ctx) => {
        if (!ctx.state.user || !ctx.state.user.id) {
            return ctx.response.status = 401;
        }
        const billingData = ctx.request.body.billingAddress;
        await strapi.entityService.update('plugin::users-permissions.user', ctx.state.user.id, {
            data: {
                billingAddress: {
                    firstName: billingData.firstName,
                    lastName: billingData.lastName,
                    company: billingData.company,
                    address1: billingData.address1,
                    city: billingData.city,
                    country: billingData.country,
                    provinceOrState: billingData.provinceOrState,
                    zipCode: billingData.zipCode,
                    phone: billingData.phone,
                    email: billingData.email,
                },
            },
            populate: ["billingAddress"],
        }).then((res) => {
            ctx.response.status = 200;
        })
    }

    plugin.routes['content-api'].routes.push(
        {
            method: "PUT",
            path: "/user/me",
            handler: "user.updateMe",
            config: {
                prefix: "",
                policies: []
            }
        }
    )

    return plugin;
}
英文:

By using entityService and doing some tweaking with data and populate parameters I was able to get this working with following code:

module.exports = (plugin) => {
    plugin.controllers.user.updateMe = async (ctx) => {
        if (!ctx.state.user || !ctx.state.user.id) {
            return ctx.response.status = 401;
        }
        const billingData = ctx.request.body.billingAddress;
        await strapi.entityService.update('plugin::users-permissions.user', ctx.state.user.id, {
            data: {
            billingAddress: {
                firstName: billingData.firstName,
                lastName: billingData.lastName,
                company: billingData.company,
                address1: billingData.address1,
                city: billingData.city,
                country: billingData.country,
                provinceOrState: billingData.provinceOrState,
                zipCode: billingData.zipCode,
                phone: billingData.phone,
                email: billingData.email,
            },
            },
            populate: ["billingAddress"],
        }).then((res) => {
            ctx.response.status = 200;
        })
    }

    plugin.routes['content-api'].routes.push(
        {
            method: "PUT",
            path: "/user/me",
            handler: "user.updateMe",
            config: {
                prefix: "",
                policies: []
            }
        }
    )

    return plugin;
}

huangapple
  • 本文由 发表于 2023年1月10日 18:34:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/75068703.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定