![](/img/trans.png)
[英]SQL/TypeORM - How do you represent the "many" part of a one-to-many relation as multiple tables?
[英]How to include the 'many' part of a relation from the 'one of many' model?
我正在嘗試獲得一種產品,包括它屬於其中的類別。 一個類別當然有許多產品,而產品是一個類別的一部分。 我是這樣的
Product.find({include: 'Categories'})
當我嘗試執行此查詢時,出現錯誤。 “未為產品模型定義“類別”關系”。
我已根據此處找到的回送文檔定義了這種關系: https : //docs.strongloop.com/display/public/LB/HasMany+relations 。 作為一個類別有許多產品。 如下所示:
category.json
"relations": {
"products": {
"type": "hasMany",
"model": "Product",
"foreignKey": "categoryId"
}
},
在products.json中未定義任何內容。 當然,我已經檢查了復數形式,但它們都已檢出。
當我嘗試獲取所有類別的所有產品時,它可以正常工作。 我很確定這是有意的。 但是我應該怎么做呢? 我已經嘗試將Product中的關系定義為hasOne,在這里記錄: https ://docs.strongloop.com/display/public/LB/HasOne+relations。 但這需要在另一個對象中使用外鍵,因此顯然僅意味着一對一關系。 除此之外,我有些困惑……有什么想法嗎?
從產品方面添加它時,必須在product.json中創建該關系
正如您提到的,產品僅屬於一個類別-這意味着關系名稱應為類別。
將其視為類似,回送將調用函數Product.category
在product.json中添加以下代碼段
"relations": {
"category": {
"type": "belongsTo",
"model": "Category",
"foreignKey": "categoryId"
}
},
現在嘗試-
Product.find({include: 'category'})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.