2017-05-13 182 views
0

我知道,在船帆我可以用填充連接兩個模型,如在這個環節Sails model and orm 例如描述我有2個型號:如何使用連接到連接兩個表中帆

// myApp/api/models/Pet.js 
module.exports = { 
    attributes: { 
    name: { 
     type: 'string' 
    }, 
    color: { 
     type: 'string' 
    } 
    } 
} 

// myApp/api/models/User.js 
module.exports = { 
    attributes: { 
    name: { 
     type: 'string' 
    }, 
    age: { 
     type: 'integer' 
    }, 
    pony:{ 
     model: 'pet' 
    } 
    } 
} 

然後

User.find({ name:'Mike' }) 
.populate('pony') 
.exec(function(err, users) {} 

將返回結果的東西像

[{ 
    name: 'Mike', 
    age: 21, 
    pony: { 
    name: 'Pinkie Pie', 
    color: 'pink', 
    id: 5, 
    createdAt: Tue Feb 11 2014 15:45:33 GMT-0600 (CST), 
    updatedAt: Tue Feb 11 2014 15:45:33 GMT-0600 (CST) 
    }, 
    createdAt: Tue Feb 11 2014 15:48:53 GMT-0600 (CST), 
    updatedAt: Tue Feb 11 2014 15:48:53 GMT-0600 (CST), 
    id: 1 
}] 
在這裏 小馬

是一個對象,我不喜歡這樣。我想要返回這樣的事情:

[{ 
    name: 'Mike', 
    age: 21, 
    name: 'Pinkie Pie', 
    color: 'pink', 
    id: 5, 
    createdAt: Tue Feb 11 2014 15:45:33 GMT - 0600 (CST), 
    updatedAt: Tue Feb 11 2014 15:45:33 GMT - 0600 (CST) 
    createdAt: Tue Feb 11 2014 15:48:53 GMT - 0600 (CST), 
    updatedAt: Tue Feb 11 2014 15:48:53 GMT - 0600 (CST), 
    id: 1 
}] 

(所有這些都是屬性)。所以我認爲我需要加入這種情況。我怎麼能加入?

+0

您的預期結果對象具有重複鍵。這應該是一個JS對象或JSON? – Sangharsh

+0

@Sangharsh我會在加入時重命名 – Tuan

回答

2

此問題已經涵蓋here。答案顯示在Sails for NoSQL DB中使用.populate(),在SQL DB中使用.query()。

如果您使用的是像MySQL這樣的SQL數據庫,並且這是一個頻繁運行的查詢,那麼還有一個選項是在數據庫級別創建一個視圖。您可以在MySql Documentation中找到有關創建視圖的更多信息。

+0

我認爲我會創建視圖然後 – Tuan

+0

是的,這是一個很好的選擇,那麼您可以在數據庫視圖的sails中創建模型,並且不再嵌套JSON。 – Glen