unicloud云开发进阶9-uni-id用户表与文章表foreignKey关联字段

306 阅读2分钟

tocken有过期时间,用户进入页面需要先到登录页面

      <!-- 点击进入登录页面 -->
      <navigator url="../../uni_modules/uni-id-pages/pages/login/login-withpwd.vue">点击登录</navigator>
    </view>

数据表

项目会自动创建一堆数据表结构,这些数据表schema如果不用,就不会在数据库中被创建,这些表除了前两个是之前测试时自己写的,其他的都是uni-id自动创建出来的

image.png

前面自己通过云数据库的uni-id创建了三张表,视频中是项目自动创建的

uni-id-log是保存的登录状态 image.png

image.png

uni-id-user表是用来保存用户信息的

image.png

这个user表在uni-id-users-schema中已经写好了规则

关联字段

这是之前写好的cloudDemo表规则,在这个表规则里增加一个字段啊,用来记录用户的登录状态

// 文档教程: https://uniapp.dcloud.net.cn/uniCloud/schema
{
	"bsonType": "object",
	"required": ["title"],
	"permission": {
		"read": true,
		"create": true,
		"update": false,
		"delete": false
	},
	"properties": {
		"_id": {
			"description": "ID,系统自动生成"
		},
    "title":{
      "bsonType": "string",
      // 这个title是属性,上面的title是字段名
      "title": "文章标题",
      // 说明,开发者使用
      "description": "文章的标题",
      // 修改报错信息
      "errorMessage":"标题必须填写",
      // 去掉前后的空白
      "trim": "both"
    },
    "content":{
      "bsonType": "string",
      "title": "内容",
      "description": "文章内容"
    },
    "posttime":{
      // 时间戳类型
      "bsonType": "timestamp",
      "title": "发布时间",
      "description": "文章内容",
      // 文章不通过前端传递,通过系统自动生成
      // 默认值有两个 
      // defaultValue 用户可以覆盖
      // forceDefaultValue 用户不能覆盖
      "defaultValue":{
        "$env": "now"
      }
    },
    // 阅读次数字段
    "hits":{
      "bsonType": "int",
      "title": "阅读量",
      "defaultValue":33
    }
	}
}

properties对象里新增一个字段userid,需要将cloudDemo表和uni-id-users表关联起来,用户的昵称、头像等信息发生了改变,不需要把所有信息都保存到cloudDemo里,只要在cloudDemo里记录用户ID即可

文档在unicloud的云数据库、DB Schema表结构中,在字段的属性列表这一个表格里,有关联关系foreignKey

foreignKey的属性值就是要关联的数据表.字段名,这里将users表的id字段关联过来,这样在cloudDemo数据表里的userid字段保存的就是用户ID了

还要设置一个默认值,这个默认值是通过全局变量去获取当前用户的登录id,全局变量能获取到三个值,是uniapp预置的

    "userid":{
      "bsonType": "string",
      "title": "用户id",
      "foreignKey": "uni-id-users._id",
      "defaultValue":{
        "$env": "uid"
      }
    },

回到项目首页测试,新增一条记录,点击新增按钮

      addClick(){
        db.collection("cloudDemo").add({  
          title:"unicloud",
          content:"uniclod进阶课程"
        }).then(res=>{
          // console.log(res);
          uni.showToast({
            title:"添加成功"
          })
        }).catch(err=>{
          // console.log(err.message);
          uni.showToast({
            title:err.message,
            icon:'none'
          })
        })
      },

在unicloud表的最后一条,数据已经有了,代码中传递的title和content已经有了,其他的字段是默认值,而userid就是通过表关联拿过来的uni-id-users表中的当前登录用户id

image.png

上面关联到的userid就是uni-id-udsers这张表里的当前登录用户的_id

image.png