簡體   English   中英

(續集)為什么我可以在不訪問 dataValues 屬性的情況下訪問 dataValues 中的屬性?

[英](Sequelize) Why i can access the property inside dataValues without accessing dataValues property?

為什么我可以在不訪問 dataValues 屬性的情況下訪問 dataValues 中的屬性?

例子:

const data = await Product.findAll({
    attributes: ['id', 'name', 'price', 'stock', 'sku']
});

console.log(data);

console.log(數據)的結果:

[
  Product {
    dataValues: {
      id: 1,
      name: 'Samsung Galaxy A53',
      price: 5000000,
      stock: 100,
      sku: 'SM001'
    },
    _previousDataValues: {
      id: 1,
      name: 'Samsung Galaxy A53',
      price: 5000000,
      stock: 100,
      sku: 'SM001'
    },
    uniqno: 1,
    _changed: Set(0) {},
    _options: {
      isNewRecord: false,
      _schema: null,
      _schemaDelimiter: '',
      raw: true,
      attributes: [Array]
    },
    isNewRecord: false
  },
  Product {
    dataValues: {
      id: 2,
      name: 'Samsung Galaxy S22',
      price: 10000000,
      stock: 100,
      sku: 'SM002'
    },
    _previousDataValues: {
      id: 2,
      name: 'Samsung Galaxy S22',
      price: 10000000,
      stock: 100,
      sku: 'SM002'
    },
    uniqno: 1,
    _changed: Set(0) {},
    _options: {
      isNewRecord: false,
      _schema: null,
      _schemaDelimiter: '',
      raw: true,
      attributes: [Array]
    },
    isNewRecord: false
  }
]

我想如果我想獲得“Samsung Galaxy A53”,我必須編寫如下代碼:

console.log(data[0].dataValues.name) // it is works

但為什么我可以用這樣的代碼獲得“Samsung Galaxy A53”?

console.log(data[0].name) // i can access directly to name property without using dataValues property

所有 Sequelize 模型實際上都是 DAO。
從文檔中:

A Model represents a table in the database. Instances of this class represent a database row.

Model instances operate with the concept of a dataValues property, which stores
the actual values represented by the instance.
By default, the values from dataValues can also be accessed directly from the Instance, that is:

instance.field
// is the same as
instance.get('field')
// is the same as
instance.getDataValue('field')

However, if getters and/or setters are defined for field they will be invoked,  
instead of returning the value from dataValues.
Accessing properties directly or using get is preferred for regular use,  
getDataValue should only be used for custom getters.

參見Model 部分

您無法使用data[0].name訪問該名稱,因為data[0].name不存在

如您的console.log(...)所示,對象數組的第一個元素data[0]具有以下直接屬性:

  • dataValues
  • _previousDataValues ,
  • uniqno ,
  • _changed
  • _options
  • isNewRecord

name不是主要屬性,它在dataValues中。 這就是為什么需要執行data[0].dataValues.namedata[0]["dataValues"]["name"]來獲取它的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM