How to perform SQL Joins and Relations in Sails.js and Waterline?

懵懂的女人 提交于 2019-11-30 04:45:40
particlebanana

Associations are officially Supported in Waterline

Overview

From the docs:

With Sails and Waterline, you can associate models across multiple data stores. This means that even if your users live in PostgreSQL and their photos live in MongoDB, you can interact with the data as if they lived together in the same database. You can also have associations that span different connections (i.e. datastores/databases) using the same adapter. This comes in handy if, for example, your app needs to access/update legacy recipe data stored in a MySQL database in your company's data center, but also store/retrieve ingredient data from a brand new MySQL database in the cloud.

Supported Association Types

Planned Association Types


Original Post

I'm the author of Waterline, the ORM used in Sails. Waterline is brand new and we are adding features all the time. Currently we don't have support for associations but it's next on the roadmap. We worked out an API for associations that I think most people will really like. You can view the work in progress and the proposed API at: [Proposed Sails Associations API][1].

We are going to tackle Associations and Transactions next and hope to have them ready in the next month or so.

In the mean time if you are using the MySQL or PostgreSQL adapters they both expose a raw .query() method that allows you to pass in a hand built sql query and have it executed. I totally realize this isn't ideal but should allow you to continue building your app while we get support for associations and joins.

The function signature for the query method is:

Model.query(<sql query>, <optional data>, callback);

The example from particle banana works but should actually use "new" like "var instance = new User._model(values)". I'm using the following code and it works.

Accounts.query(query, function(err, accounts) {
  if (err)
    return fn(err);

  accounts = _.map(accounts, function(account) {
    return new Accounts._model(account);
  });

  fn(null, accounts);
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!