2014-12-04 72 views
1

我注意到我沒有在帖子中獲得與我獲得的相同回覆。具體來說,協會。sails.js創建爲單向關聯的一對一關聯

參照「創建新的記錄,而關聯瓦特/另一個新紀錄」 https://github.com/balderdashy/sails-docs/blob/master/reference/blueprint-api/Create.md

我重新場景從sails new testProj,然後sails generate api ponysails generate api pet的文檔,然後更新模型有一個一對一協會。

小馬

module.exports = { 
    attributes: { 
     pet: { 
      model: 'pet' 
     } 
    } 
}; 

小馬

module.exports = { 
    attributes: { 
     pet: { 
      model: 'pet' 
     } 
    } 
}; 

寵物

module.exports = { 
    attributes: { 
     pony: { 
      model: 'pony' 
     } 
    } 
}; 

然後,sails lift之遙。

POST /pony

JSON詢價

{ 
    "name": "Pinkie Pie", 
    "hobby": "ice skating", 
    "pet": { 
    "name": "Gummy", 
    "species": "crocodile" 
    } 
} 

JSON RES

{ 
    "name": "Pinkie Pie", 
    "hobby": "ice skating", 
    "pet": 1, 
    "createdAt": "2014-11-21T19:18:09.161Z", 
    "updatedAt": "2014-11-21T19:18:09.161Z", 
    "id": 1 
} 

正如你所看到的,res ponse不包括完整的寵物對象,只是它的ID。在文檔中,它顯示了正在返回的完整對象。

的條目和協會肯定了創建成功,

GET - /pony/1

{ 
    "pet": { 
    "name": "Gummy", 
    "species": "crocodile", 
    "createdAt": "2014-11-21T19:18:09.157Z", 
    "updatedAt": "2014-11-21T19:18:09.157Z", 
    "id": 1 
    }, 
    "name": "Pinkie Pie", 
    "hobby": "ice skating", 
    "createdAt": "2014-11-21T19:18:09.161Z", 
    "updatedAt": "2014-11-21T19:18:09.161Z", 
    "id": 1 
} 

這是在文檔中的錯誤,或在代碼中的錯誤?無論哪種方式,有沒有一種方法可以指定我們想要返回關聯?

一對一關聯只是顯示爲鏈接標識,多數人根本沒有顯示出來。當我看到showJoins選項時,我正在調查waterline的另一個問題toObject()函數;它看起來可能與此有關。

此外,此一對一關聯實際上只是作爲單向關聯創建的。

完成與上述相同的後:

GET - /pet/1

{ 
    "name": "Gummy", 
    "species": "crocodile", 
    "createdAt": "2014-12-03T20:50:31.346Z", 
    "updatedAt": "2014-12-03T20:50:31.346Z", 
    "id": 1 
} 

注意,沒有返回小馬。

只是爲了確保...

GET - /pony/1/pet

{ 
    "name": "Gummy", 
    "species": "crocodile", 
    "createdAt": "2014-12-03T20:50:31.346Z", 
    "updatedAt": "2014-12-03T20:50:31.346Z", 
    "id": 1 
} 

GET - /pet/1/pony

Res

Specified record (1) is missing relation 'pony'

小馬有一個寵物,寵物有沒有小馬。

我做錯了什麼?

回答

0

您需要在定義雙向關係時提供via屬性,否則它們會被假定爲不相關的單向連接。

小馬

module.exports = { 
    attributes: { 
     pet: { 
      model: 'pet', 
      via: 'pony' 
     } 
    } 
}; 

寵物

module.exports = { 
    attributes: { 
     pony: { 
      model: 'pony', 
      via: 'pet' 
     } 
    } 
}; 

它在文檔中提到的只有在many-manyone-many關係,這可能是一個錯誤。

+1

不適用於一對多。 – 2015-05-02 00:13:56

+0

你不需要'via'進行一對一的關聯https://github.com/balderdashy/waterline-docs/blob/master/models/associations/one-to-one.md – dkx22 2015-08-18 15:35:48

+1

one-一對一關聯只能從持有外鍵的模型中工作。有關更多信息,請參閱http://stackoverflow.com/a/27752329/129808。 – oldwizard 2015-08-21 12:34:02