【问题标题】:What is ActiveRecord equivalence in the node.js world?node.js 世界中的 ActiveRecord 等价是什么?
【发布时间】:2012-07-09 10:42:29
【问题描述】:

我正在考虑将node.js 工具用于即将进行的项目,用于学习和绩效目的。 For example,Rails 中的一些模型:

class User
  has_many :topics
  has_many :friends
  has_many :friend_users, :through => :friends
  has_many :friend_topics, :through => :friend_users, :source => :topics      
end

class Friend
  belongs_to :user
  belongs_to :friend_user, :class_name => "User", 
      :foreign_key => :phone_no, :primary_key  => :phone_no
end

class Topic
  belongs_to :user
end

允许优雅的查询代码,例如:

latest_10_topics_from_friends = current_user.friend_topics.limit(10)

并生成优化的 SQL。 node.js 生态系统中是否有类似的东西?

【问题讨论】:

  • 最有可能是 mysql 或 postgre。
  • 签出sailsjs.org

标签: ruby-on-rails node.js activerecord


【解决方案1】:

Waterline 似乎正是您要找的东西。它是由 Sails 项目背后的同一个人创建的。

https://github.com/balderdashy/waterline

【讨论】:

  • 我有一个简单的问题:有没有办法在不定义模型属性的情况下让水线工作?就像在这里是可能的:github.com/3kg4kR/active_record
  • Waterline 不能正确支持多对多关系,更不用说“通过”关系了。
  • @morbaq Waterline 实际上 100% 支持多对多关系。
【解决方案2】:

更新答案

使用sequelize


旧答案:

查看Tower 项目。您可以按如下方式定义模型:

# app/models/user.coffee
class App.User extends Tower.Model
  @belongsTo "author", type: "User"
  @belongsTo "commentable", polymorphic: true
  @has_many "topics"
  @has_many "friends"
  @has_many "friend_users", through: "friends"
  @has_many "friend_topics", through: "friends_users", source: "topics"

# app/models/friend.coffee
class App.Friend extends Tower.Model
  @belongs_to "user"
  @belongs_to "friend_user", type: "User", 
                foreign_key: "phone_no", primary_key: "phone_no"

# app/models/topic.coffee
class App.Topic extends Tower.Model
  @belongs_to "user"

现在您将能够查询您的数据

current_user.friend_topics().limit(10)

【讨论】:

  • 对于截至 2015 年阅读本文的任何人,根据他们的文档,Tower 现在没有维护,1-2 年内没有新的提交。继续看……
  • 是的,塔完全死了。建议更新答案。
  • sequelize 是节点对 orm 的回答,但与 activerecord 相比它是垃圾。 Activerecord 很简单,sequelize 很冗长。
【解决方案3】:

如果你使用的是 MySql,你可以试试 Sequelize.js。 很难达到 ActiveRecord 提供的功能数量,但尽管如此,我一直在使用 Sequelize,它是 Node.js 的一个很好的解决方案

其他数据库还有其他几种ORM解决方案,你可以在这里查看http://search.npmjs.org/

【讨论】:

    【解决方案4】:

    mongoose 可能是最接近的类比,尽管它是针对文档存储而不是像 rails/active record 这样的关系数据库

    【讨论】:

    • 虽然猫鼬可能不是 OP 正在寻找的东西,但它在这里是一个合法的答案。它具有 ActiveRecord 的许多功能,尽管它与 MongoDB 而不是 SQL 数据库相关联。
    猜你喜欢
    • 2013-07-22
    • 2011-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多