使用以下模型,我正在寻找一种有效且直接的方法来返回所有具有 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
谢谢!