2014-09-26 70 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