Sequelize V6.20.1 MVC模式(四 | 一对一)

大家可以前往 Sequelize中文文档,查看 Sequelize不同版本【5.x、4.x】的文档

本文档分多个篇章,难易程度从低到高,学习此篇章之前,务必确保自己已经掌握 node.js、express、es6语法、mysql等关系型数据库的sql语法等

一对一

以下例子可能不恰当,但是不要较真,跟着思路走就对了。
举个栗子: 假设一个人(id)只能有一个爱好,而一个爱好(id)也只能对应一个人,那么这种模式就是一对一

模型定义

我这里为了方便理解就不把hobbys表的模型拎出去了

import {Sequelize, DataTypes} from 'sequelize'
import sequelize from './../connection'

const User = sequelize.define('user', {
    username: DataTypes.STRING,
    gender: {
        type: DataTypes.INTEGER,
        defaultValue: 1,
    },
    age: {
        type: DataTypes.INTEGER,
        defaultValue: 20
    },
    headImg: {
        type: DataTypes.STRING,
        defaultValue: 'img.png'
    }
});
const Hobby = sequelize.define('hobby',
    {
        hobbyName: {
            type: DataTypes.CHAR(20),
            allowNull: false
        }
    }
);

//User的实例对象将拥有getHobby、setHobby、createHobby方法
User.hasOne(Hobby);
//Hobby的实例对象将拥有getUser、setUser、createUser方法
Hobby.belongsTo(User);

User.sync({force: true}).then(d=> {//创建完成之后注释掉此段
    console.log('users表同步完成');
    Hobby.sync({force: true}).then(d=> {
        console.log('Hobby表同步完成');
    });
});

export default {User,Hobby}

关系操作

增加数据

客户端传来 username hobbyName

User.Controller.js

insertUserHobby: async (req, res, next) => {
        let {username, hobbyName} = req.body;
        let user = await User.User.create({username});
        let hobby = await user.createHobby({hobbyName});
        res.send({
            code: 200,
            hobby
        })
    }

postman

{
    "code": 200,
    "hobby": {
        "id": 4,
        "hobbyName": "rap",
        "userId": 18,
        "updatedAt": "2019-07-10T04:12:50.770Z",
        "createdAt": "2019-07-10T04:12:50.770Z"
    }
}
修改数据

通过用户id,修改关联的hobbyName

User.Controller.js

updateUserHobby: async (req, res, next)=>{
        let {id, hobbyName} = req.body;
        let user = await User.User.findOne({where: {id}});//通过id查询用户
        let upHobby = await User.Hobby.create({hobbyName});//在hobbys表中创建一条数据
        let updateHobby = await user.setHobby(upHobby);//找出当前user所关联的hobbyName并将其userId置为null(为了保证一对一关系),然后设置当前插入的数据的userId为当前的用户id
        res.send({
            code: 200,
            data: '修改成功',
            updateHobby
        })
    }

数据库

修改数据

postman

{
    "code": 200,
    "data": "修改成功",
    "updateHobby": {
        "id": 6,
        "hobbyName": "唱跳rap",
        "updatedAt": "2019-07-10T04:23:19.565Z",
        "createdAt": "2019-07-10T04:23:19.537Z",
        "userId": 18
    }
}
删除数据

通过用户id删除对应的hobby 实际上是清空绑定,将userId设置为Null

User.Controller.js

deleteUserHobby: async (req, res, next)=>{
        let {id} = req.body;
        let user = await User.User.findOne({where: {id}});//通过id查询用户
        let deleteHobby = await user.setHobby(null);
        res.send({
            code: 200,
            data: '删除成功',
            deleteHobby
        })
    }

postman

{
    "code": 200,
    "data": "删除成功",
    "deleteHobby": null
}
查找数据

查询用户所对应的hobby,只返回hobby

User.Controller.js

getHobby: async (req, res, next)=>{
        let {id} = req.query;
        let user = await User.User.findOne({where: {id}});//通过id查询用户
        let hobby = await user.getHobby();
        res.send({
            code: 200,
            hobby
        })
    }

postman

{
    "code": 200,
    "hobby": {
        "id": 7,
        "hobbyName": "唱跳rap",
        "createdAt": "2019-07-10T04:37:23.000Z",
        "updatedAt": "2019-07-10T04:37:23.000Z",
        "userId": 18
    }
}

查询用户所对应的hobby,user和对应的hobby一同返回

User.Controller.js

getUserAndHobby: async (req, res, next)=>{
        let {id} = req.query;
        let userAndHobby = await User.User.findByPk(id,{
            include: [User.Hobby],
            attributes: ['id', 'username', 'age']
        });
        res.send({
            code: 200,
            userAndHobby
        })
    }

postman

{
    "code": 200,
    "userAndHobby": {
        "id": 18,
        "username": "Anmy",
        "age": 20,
        "hobby": {
            "id": 7,
            "hobbyName": "唱跳rap",
            "createdAt": "2019-07-10T04:37:23.000Z",
            "updatedAt": "2019-07-10T04:37:23.000Z",
            "userId": 18
        }
    }
}

好了,到此为止,一对一的关系就已经结束了,下一章节我们会介绍 [Sequelize V6.20.1 中数据表的关系:一对多

你可能感兴趣的:(Sequelize V6.20.1 MVC模式(四 | 一对一))