简体   繁体   English

Axios 从另一个表调用映射数据 - ReactJs

[英]Axios call mapping data from another table - ReactJs

I am building a React web application that has CRUD operations on a table connected to a database.我正在构建一个 React web 应用程序,它对连接到数据库的表进行 CRUD 操作。 I am using axios libraries to get/post requests to and from my api controller, and then mapping the data to my sales array.我正在使用 axios 库从我的 api controller 获取/发布请求,然后将数据映射到我的销售数组。 The Sales array contains list of records from the Sales table which has a many-to-one relationship to with my Customer, Products and Store tables. Sales 数组包含 Sales 表中的记录列表,该表与我的 Customer、Products 和 Store 表具有多对一关系。 The fetch results only shows the id numbers of customer, products and stores but I want it to get the customer, product and store objects and store them in its own array.获取结果只显示客户、产品和商店的 ID 号,但我希望它获取客户、产品和商店对象并将它们存储在自己的数组中。 The axios calls is only getting back null objects. axios 调用仅返回 null 个对象。

How would i go about solving this?我 go 如何解决这个问题? Would i need to make 4 API calls: first one to get a list of referenced IDs from the sales table and pass each ID to the the Customers, Products and Stores component to fetch the data?我是否需要进行 4 次 API 调用:第一个调用从销售表中获取引用 ID 的列表并将每个 ID 传递给客户、产品和商店组件以获取数据? Would this require uplifting the array states to the Sales component?这是否需要将数组状态提升到销售组件?

0:
customer: null
customerId: 1
dateSold: "2020-10-29T00:00:00"
id: 2
product: null
productId: 1
store: null
storeId: 1
__proto__: Object
1:
customer: null
customerId: 2
dateSold: "2020-10-27T00:00:00"
id: 3
product: null
productId: 3
store: null
storeId: 1

export class Sales extends Component {
  constructor(props) {
    super(props);
    this.state = { sales: [], };
    this.populateSalesData = this.populateSalesData.bind(this);
  }

  componentDidMount() {
    this.populateSalesData();
  }

  populateSalesData = () => {
    axios.get("Sales/GetSales")
      .then((result) => {
        this.setState({ sales: result.data })
        console.log(result.data);
      })
      .catch((error) => {
        console.log(error);
      });
  }

this is not the client-side request job to handle your schema relations.这不是处理您的架构关系的客户端请求作业。

to access customer and product of a sale you should change your api .要访问销售的客户和产品,您应该更改您的 api

when you request to Sales/GetSales GetSales should loop through every sale in your当您请求Sales/GetSales时,GetSales 应该遍历您的每个销售

database and for each sale find the relative customer by customerId inside sale object and数据库并为每个销售找到相关客户通过 customerId inside sale object 和

set it to result.将其设置为结果。

below we can see a simple example wrote in nodejs and mongoose.下面我们可以看到一个用nodejs和mongoose写的简单例子。

// inside api

const sales = await Sale.find({});
sales.map((sale) => {
  sale.customer = await Customer.find({id: sale.customerId})
});

return sales.

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

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