2014-11-03 104 views
1

我是新來Sails並創建一個簡單的應用程序。
我現在卡在數據模型中。
User模型如下:如何從現有的模型創建新的帆模型

module.exports = { 

attributes: { 
    firstName: { 
     type: 'string' 
    }, 
    lastName: { 
     type: 'string' 
    }, 
    email: { 
     type: 'email', 
     required: true 
    }, 

    password: { 
     type: 'String' 
    }, 
    passwordSalt: { 
    type: 'String' 
    }, 
    projects:{ 
    collection: 'ProjectMember', 
    via: 'userId' 
    } 
    } 
}; 

我需要叫TinyUser多了一個模型,它得到了一些屬性從用戶(喜歡外國的關鍵用戶),這樣我就可以訪問,而不是直接訪問UserTinyUser
TinyUser模型如下:

module.exports = { 
tableName: 'User', 
    attributes: { 
    firstName:{ 
    type: 'string' 
    }, 
    lastName: { 
     type: 'string' 
    }, 
    email: { 
     type: 'email' 
    } 
} 
}; 

ProjectMember模型如下:

module.exports = { 

attributes: { 

    projectId: { 
     model: 'Project' 
    }, 
    userId: { 
     model: 'TinyUser' 
    }, 
    projectRole: { 
     model: 'ProjectRole' 
    }, 

} 
}; 

在帆,反正我有可以節省TinyUser數據,而不實際創建,但只是抱着一些屬性用戶表數據?

要說清楚,如果有另一個名爲Task的表,它試圖訪問用戶數據,那麼TinyUser作爲模型而不是用戶是更好的選擇,因爲它只包含所需的信息。用於任務而不是存儲用戶所做的所有其他字段。

有什麼辦法可以解決這個問題嗎? 在前感謝

回答

1

你的意思是你需要從「User」模型繼承「TinyUser」嗎?

你可以這樣做。

/api/services/baseUserModel.js:

module.exports = { 
 

 
    attributes: { 
 
    firstName: 'string', 
 
    lastName: 'string', 
 
    email: { 
 
     type: 'email', 
 
     required: true 
 
    }, 
 
    password: 'string', 
 
    passwordSalt: 'string', 
 
    projects: { 
 
     collection: 'ProjectMember', 
 
     via: 'userId' 
 
    } 
 
    } 
 
};

/api/models/TinyUser.js:

var baseUserModel = require('../services/baseUserModel'), 
 
    _ = require('lodash'); 
 

 
module.exports = _.merge({ 
 
    tableName: 'User', 
 
    attributes: { 
 
    firstName: 'string', 
 
    lastName: 'string', 
 
    email: { 
 
     type: 'email', 
 
     required: true 
 
    } 
 
    } 
 
}, baseUserModel);

而ProjectMem BER模式應該是:

module.exports = { 
 

 
    attributes: { 
 

 
    projectId: { 
 
     model: 'project' 
 
    }, 
 
    userId: { 
 
     model: 'tinyuser' 
 
    }, 
 
    projectRole: { 
 
     model: 'projectrole' 
 
    } 
 

 
    } 
 
};

+0

我得到了嘗試此以下錯誤: 錯誤:試圖集合屬性不具有外鍵的模型相關聯。 tinyuser正在嘗試在References.findReference中引用項目成員中的外鍵.... 任何想法爲什麼會出現此錯誤? – Abhishek 2014-11-04 07:44:53

+1

您能否提供「ProjectMember」模型的代碼,您應該注意的一點是,在「ProjectMember.js」中,相關屬性應該是這樣的:'userid:{model:'tinyuser'}, 。請參考[官方文檔](http://sailsjs.org/#/documentation/concepts/ORM/Associations/OnetoMany.html) – 2014-11-04 09:07:31

+0

我已經使用ProjectMember Model更新了我的問題,錯誤仍然相同,用戶嘗試在項目成員中引用一個外鍵。 – Abhishek 2014-11-04 09:36:03

相關問題