繁体   English   中英

查询两个表中的sequelize

[英]querying two tables in sequelize

肯定有一些方法可以用更少的代码行来完成。

数据库不是我最强的数据库,而我是新手。 用户ID作为参数输入,我必须检查用户表中是否有用户。 如果没有用户只是发回,则没有用户,否则请检查图片表以查看用户是否有图片。 userid是pics表中的外键。 如果用户没有图片,我给他们一个默认的其他方式,我将他们的图片设置为数据库中存储的图片。 我有它的工作,但我知道它可以用findAll和include更少的代码行来写得更好,但是我无法理解。 任何帮助表示赞赏。 这是有效的代码。

users.findById(userId)
    .then(function (user) {
        if (!user) {
            res.render('error', {
                message: 'No user found with id of ' + userId,
                error: {
                    status: 404
                }
            });
        } else {
            pics.findOne({
                where: {
                    user_id: userId
                },
                attributes: ['profile_pic_filename']
            }).then(function (pic) {
                if (!pic) {
                    //if no pic give a default
                    profilepic = process.env.DEFAULT_PROFILE_PIC;
                } else {
                    profilepic = CDNPath + pic.profile_pic_filename;
                }

                res.render('user', {
                        profilePic: profilepic,
                        firstname: user['first_name'],
                        username: user['username'],
                        surname: user['surname'],
                        email: user['email']}
                );
            });
        }
    });

肯定有一些方法可以用更少的代码行来完成。

如果将其最小化,可以将它们全部放在一行上:D!

开玩笑...

.findOne函数返回一个promise

与回调不同的是,如果出现错误,则抛出的错误将被伴随的catch函数捕获 您需要做的就是将错误放在陷阱中,不要打扰第一个查询。

pics.findOne({ where: { user_id: userId }, attributes: ['profile_pic_filename']})
    .then(pic => {
        var profilepic = process.env.DEFAULT_PROFILE_PIC;
        if (pic) profilepic = CDNPath + pic.profile_pic_filename;

        res.render('user', {
            profilePic: profilepic,
            firstname: user['first_name'],
            username: user['username'],
            surname: user['surname'],
            email: user['email']}
        );
    })
    .catch(e => {
        // test the error is what you were expecting.
        return res.render('error',
            { message: 'No user found with id of ' + userId, error: { status: 404 }});
    });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM