2

使用以下模型,我正在寻找一种有效且直接的方法来返回所有具有 0 个父任务的任务(本质上是顶级任务)。我最终也想返回 0 个子任务之类的东西,所以一个通用的解决方案会很棒。这是否可以使用现有的 DataMapper 功能,或者我需要定义一种方法来手动过滤结果?

class Task
  include DataMapper::Resource

  property :id,    Serial
  property :name , String, :required => true

  #Any link of type parent where this task is the target, represents a parent of this task 
  has n, :links_to_parents, 'Task::Link', :child_key => [ :target_id ], :type => 'Parent'
  #Any link of type parent where this task is the source, represents a child of this task
  has n, :links_to_children, 'Task::Link', :child_key => [ :source_id ], :type => 'Parent'

  has n, :parents, self,
    :through => :links_to_parents,
    :via => :source

  has n, :children, self,
    :through => :links_to_children,
    :via => :target

  def add_parent(parent)
    parents.concat(Array(parent))
    save
    self
  end

  def add_child(child)
    children.concat(Array(child))
    save
    self
  end

  class Link
    include DataMapper::Resource

    storage_names[:default] = 'task_links'

    belongs_to :source, 'Task', :key => true
    belongs_to :target, 'Task', :key => true
    property :type, String
  end

end

我希望能够在 Task 类上定义一个共享方法,例如:

def self.without_parents
   #Code to return collection here
end

谢谢!

4

1 回答 1

4

DataMapper 在这些情况下会失败,因为实际上您正在寻找的是 LEFT JOIN 查询,其中右侧的所有内容都是 NULL。

SELECT tasks.* FROM tasks LEFT JOIN parents_tasks ON parents_tasks.task_id = task.id WHERE parents_tasks.task_id IS NULL

您的父母/孩子的情况在这里没有什么不同,因为它们都是 n:n 映射。

单独使用 DataMapper(至少在 1.x 版中)最有效的是:

Task.all(:parents => nil)

这将执行两个查询。WHERE task_id NOT NULL第一个NOT IN是来自 n:n 数据透视表(

不幸的是,我认为您将不得不自己编写 SQL ;)

编辑 | https://github.com/datamapper/dm-ar-finders它的 find_by_sql 方法可能很有趣。如果字段名称抽象对您很重要,您可以在 SQL 中引用Model.storage_nameModel.some_property.field

于 2011-10-01T01:10:14.430 回答