2014-09-26 72 views
1

我有兩個型號Sails.js協會填充不同的連接

國家 - 從MySQL服務器

Country = { 
    tableName: 'countries', 
    connection: 'someMysqlServer', 

    schema: true, 
    migrate: 'safe', 
    autoCreatedAt: false, 
    autoUpdatedAt: false, 

    attributes: { 
    country_id: { 
     type: 'integer', 
     primaryKey: true, 
     autoIncrement: true 
    }, 
    .... 
    } 
}; 

User = { 
    connection: 'somePostgresqlServer', 

    attributes: { 
     id: { 
      type: 'integer', 
      primaryKey: true, 
      autoIncrement: true 
     }, 

     country_id: { 
      model: 'country' 
     }, 

$> User.findOneById(1).populate( 'COUNTRY_ID')EXEC(控制檯.LOG)

,並得到錯誤

sails> Error (E_UNKNOWN) :: Encountered an unexpected error 
: Unable to determine primary key for collection `countries` because an error was encountered acquiring the collection definition: 
[TypeError: Cannot read property 'definition' of undefined] 
    at _getPK (/projects/foturist-server/node_modules/sails-postgresql/lib/adapter.js:923:13) 
    at StrategyPlanner.__FIND__.Cursor.$getPK (/projects/foturist-server/node_modules/sails-postgresql/lib/adapter.js:504:20) 
..... 

Details: Error: Unable to determine primary key for collection `countries` because an error was encountered acquiring the collection definition: 
[TypeError: Cannot read property 'definition' of undefined] 

爲什麼國家協會與postgre-連接使用?

回答

0

那麼,由於這兩個模型是在不同的數據庫連接,你不能夠做​​一個實際的SQL連接。我想什麼你需要的是一個

User.find({id: 1}).exec(function(user) { 
    var theUser = user; 
    Country.find(user.country_id) 
    .exec(function(country) { 
     theUser.country = country; 
     return theUser; 
    }); }); 

我不知道你要處理哪些具體需求,但由於國家的查找表是不太可能頻繁變化,而且是在一個完全不同的數據存儲,我建議將這些數據緩存在Redis或Memcache之類的東西中。然後在您的用戶查找回調中,您可以通過緩存存儲區中的id獲取國家/地區。除非您預期這些數據會定期更改,否則速度會更快。您可以編寫一個服務,在您的其他數據庫中進行惰性查找,然後從緩存中提供服務,或者在應用啓動時將其全部緩存起來。

+0

感謝您的回答 但我如果使用{rest:true},那麼這個代碼將會自動生成。 關於服務查找 - 我想。 Elasticsearch – zoh 2014-09-27 06:53:34