首页 > 解决方案 > TypeORM - 如何在javascript中访问另一个对象内的相关对象

问题描述

我在显示另一个对象内部的对象的属性时遇到问题...我在后端与 TypeORM 建立了关系,使用关系将部门带入用户,但我不能在用户请求中使用它们,因为请求以[[prototype]].

import { getUsersDataId } from 'services/usuarios'
import store from 'store'

const General7 = () => {
  const [users, setUsers] = useState({})

  const id = store.get('id')

  const getUsers = async () => {
    const data = await getUsersDataId(id)
    setUsers(data)
  }

  useEffect(() => {
    getUsers()
  }, [])

  console.log(users)


  return (
    <div>
      <div className="d-flex flex-wrap align-items-center mb-2">
        <div className="flex-shrink-0 vb__utils__avatar mr-4 mb-2">
          <img src="resources/images/avatars/5.jpg" alt="Mary Stanform" />
        </div>
        <div className="mb-2">
          <div className="text-dark font-size-18 font-weight-bold text-nowrap">
            {users.name}
            <i className="align-text-bottom fe fe-check-square text-success ml-2 font-size-24 " />
          </div>
          <div className="text-uppercase">Support team</div>
        </div>
      </div>
      <div className="mb-3">
        <a className="btn btn-outline-primary mr-2">Chat</a>
        <a className="btn btn-outline-danger">Unfollow</a>
      </div>
      <div className="table-responsive">
        <table className="table table-borderless">
          <tbody>
            <tr>
              <td className="text-gray-6 pl-0">Departamento</td>
              <td className="pr-0 text-right text-dark">{users.department.name}</td>
            </tr>
            <tr>
              <td className="text-gray-6 pl-0">Ocupação</td>
              <td className="pr-0 text-right text-dark">{users.occupation}</td>
            </tr>
            <tr>
              <td className="text-gray-6 pl-0">Tempo de Experiência</td>
              <td className="pr-0 text-right text-dark">{users.timeExperience}</td>
            </tr>
            <tr>
              <td className="text-gray-6 pl-0">Email</td>
              <td className="pr-0 text-right text-dark">{users.email}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  )
}

export default General7


getUsers() 函数返回以下结果

{id: 29, profileId: 1, name: 'Thiago Gouvêa', email: 'thiagosng@gmail.com', password: '$2a$08$9yGZGer452gOfSa2h0mUwu92Xq.038fx2pV7nEV3XLPSuuyxBJPnC', …}
active: true
avatar: null
createdAt: "2021-10-09T02:49:22.871Z
"createdBy: null
departmentId: 1
email: "thiagosng@gmail.com
"forgottenPasswordCode: null
forgottenPasswordTime: null
id: 29
lastAccess: null
name: "Thiago Gouvêa"
occupation: "Desenvolvedor front-end"
password: "$2a$08$9yGZGer452gOfSa2h0mUwu92Xq.038fx2pV7nEV3XLPSuuyxBJPnC"
profileId: 1
timeExperience: 2
updatedAt: null
[[Prototype]]: Object

我需要访问原型中的内容,如下所示

 {
    "id": 29,
    "profileId": 1,
    "name": "Thiago Gouvêa",
    "email": "thiagosng@gmail.com",
    "password": "$2a$08$9yGZGer452gOfSa2h0mUwu92Xq.038fx2pV7nEV3XLPSuuyxBJPnC",
    "occupation": "Desenvolvedor front-end",
    "departmentId": 1,
    "timeExperience": 2,
    "avatar": null,
    "lastAccess": null,
    "active": true,
    "forgottenPasswordCode": null,
    "forgottenPasswordTime": null,
    "createdAt": "2021-10-09T02:49:22.871Z",
    "updatedAt": null,
    "createdBy": null,
    "department": {
      "id": 1,
      "name": "Desenvolvimento",
      "description": "Departamento dos Devs"
    }
  }

我正在尝试返回部门值但是当我使用 users.department.name 时返回未定义

我查询用户的后端路线也是如此

usersRouter.get('/', async (request, response) => {   
  const usersRepository = getCustomRepository(UsersRepository);   
  const users = await usersRepository.find({     
    relations: ['department'],
  });    
  return response.json(users); 
}); 

标签: javascriptnode.jstypeorm

解决方案


除非您的user->department关系设置为eager,否则您需要加载惰性关系。

例如:

const user = await connection.getRepository(User).findOne(1);
const department = await user.department;
// you'll have all user's department inside "department" variable now

否则,您可以尝试使您的关系eager像这样:

@Entity('users')
class User {
    ...

    @ManyToMany(type => Department, department => department.name, {
        eager: true
    })

    @JoinTable()

    department: Department[];

}

每次从数据库加载实体时,都会自动加载急切关系。

查看急切和懒惰的关系


推荐阅读