【问题标题】:Self joins in Batmanjs自我加入 Batmanjs
【发布时间】:2014-06-29 21:58:38
【问题描述】:

如何在 Batmanjs 中实现自联接?

在 Rails 中,如发现 here,它是这样的:

class Employee < ActiveRecord::Base
  has_many :subordinates, class_name: "Employee", foreign_key: "manager_id"
  belongs_to :manager, class_name: "Employee"
end

我当前的 Batmanjs 等效模型如下所示:

class Employee extends Batman.Model
  @resourceName: 'employees'
  @storageKey: 'employees'

  @persist Batman.LocalStorage

  @has_many 'subordinates', name: "Employees", foreignKey: "manager_id"
  @belongs_to 'manager', name: "Employee"

【问题讨论】:

    标签: self-join batman.js


    【解决方案1】:

    我认为这应该可以,如果你只是切换:

    • has_many/belongs_to => hasMany/belongsTo
    • name: "Employees" => name: "Employee"

    此外,您可能必须使用 LocalStorage 适配器为 id 添加编码器。 LocalStorage 将值转换为字符串,但 batman.js 需要一个整数,因此您必须在编码器中将其强制转换为整数。

    这是自连接的示例(您也可以从那里复制粘贴编码器):

    http://jsbin.com/cukapedo/18/edit

    为后代粘贴在这里:

    class App.Color extends Batman.Model 
      @resourceName: 'color'
      @persist Batman.LocalStorage
      @encode 'name', 'source_color_id'
      # required for numbers in localStorage:
      @encode 'id', 
        encode: (val) -> +val
        decode: (val) -> +val
    
      @hasMany 'child_colors', name: 'Color', foreignKey: 'source_color_id'
      @belongsTo 'source_color', name: 'Color'
    

    【讨论】:

    • 这行得通,谢谢。我的问题可能出在测试中:在 setup 函数中,命令 red.get('child_colors') 返回 undefined。
    • 哦,我不敢相信我错过了——您使用的是hasManybelongsTo,而不是has_many/belongs_to? (也将此添加到答案中)
    • 是的,我的错对不起,我已经改变了。一切正常,除了当我从 Batman.TestCase 中的 setup 函数调用命令时。
    • 我认为它查找与 Batman.currentApp 的关联,直到您调用 MyApp.run() 才定义。在您的测试设置中,请致电MyApp.run() 或自己分配Batman.currentApp = MyApp。这行得通吗??
    • 很高兴听到这个消息——下一个版本的 Batman.js 将自行提供此信息 :) github.com/batmanjs/batman/pull/1072
    猜你喜欢
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-24
    • 2015-10-18
    • 2021-02-06
    相关资源
    最近更新 更多