本项目是基于uni-start进行修改的。整体功能是为了实现每个老师根据自己登录的账号显示或查找自己的学生,而不能查看其他老师的学生的信息。
在学生信息表的schema中使用了foreignKey,定义了user_id(位于uni-id-users表,这张表存放的是老师信息),代码如下:
学生信息表的schema为
"bsonType": "object",
"required": ["stunum", "name", "banji"],
"permission": {
"read": "doc.user_id == auth.uid",
"create": "doc.user_id == auth.uid",
"update": "doc.user_id == auth.uid",
"delete": "doc.user_id == auth.uid"
},
"properties": {
"_id": {
"description": "ID,系统自动生成"
},
"user_id": {
"bsonType": "string",
"description": "老师id",
"foreignKey": "uni-id-users._id",
"defaultValue": {
"$env": "uid"
}
},
"stunum": {
"bsonType": "string",
"title": "学号",
"trim": "both"
},
"name": {
"bsonType": "string",
"title": "姓名",
"trim": "both"
},
"banji": {
"bsonType": "string",
"title": "班级",
"trim": "both"
},
使用schema2code生成了list.vue/add.vue/detail.vue/edit.vue四个页面,其中的list.vue页面中数据渲染部分的代码如下:
<template>
<view>
<view class="search-box">
<uni-search-bar :focus="true" @input="onKeyInput" placeholder="姓名、学号"></uni-search-bar>
</view>
<view class="container">
<unicloud-db ref="udb" v-slot:default="{data, pagination, loading, hasMore, error}" :collection="collectionList"
:where="where"
field="stunum,name,banji,tel,user_id">
<uni-card title="以下名单为所有学生" extra="请注意保护学生隐私">
<view v-if="error">{{error.message}}</view>
<view v-else-if="data">
<uni-list>
<uni-list-item v-for="(item, index) in data" :key="index" showArrow :clickable="true"
@click="handleItemClick(item._id)">
<template v-slot:body>
<text>
{{item.stunum}}   {{item.name}}
</text>
</template>
</uni-list-item>
</uni-list>
</view>
<uni-load-more :status="loading?'loading':(hasMore ? 'more' : 'noMore')"></uni-load-more>
</uni-card>
</unicloud-db>
<!-- <uni-fab ref="fab" horizontal="right" vertical="bottom" :pop-menu="false" @fabClick="fabClick" /> -->
</view>
</view>
</template>
where的代码如下:
where() {
return 'user_id == $cloudEnv_uid'
// dbCmd.or(
// {['name']:new RegExp(this.searchVal, 'gi')},
// {['stunum']:new RegExp(this.searchVal, 'gi')},
// {['tel']:new RegExp(this.searchVal, 'gi')},
// {['banji']:new RegExp(this.searchVal, 'gi')},
// )
}
这里使用'user_id == $cloudEnv_uid'是为了获取用户权限,如果不使用的话就会提示【PERMISSION_ERROR 权限校验未通过】和【Error: 权限校验未通过】,但是这样就不能模糊搜索了。如果仅使用dbcmd.or后的代码则不仅不能进行模糊搜索还会提示【权限校验未通过】,不会显示任何学生信息。
辛苦开发者回答,这个问题困扰了好几天了都没解决,谢谢您~
2 个回复
DCloud_uniCloud_WYQ
或者使用上述写法对应的对象格式写法
1***@qq.com (作者)
卧槽,你太牛了,谢谢大佬【抱拳】