维护 DataMapper 有序多对多关联
我有一个 DataMapper 多对多关系,朋友们,需要将其保存在 命令。维持秩序的最佳方式是什么?我下了订单财产 在连接模型中,但似乎无法找出更新它的好方法。
我的代码:
class Person
include DataMapper::Resource
property :id, Serial
property :name , String, :required => true
has n, :friendships, :child_key => [ :source_id ]
has n, :friends, self, :through => :friendships, :via => :target
end
class Friendship
include DataMapper::Resource
property :source_id, Integer, :key => true, :min => 1
property :target_id, Integer, :key => true, :min => 1
property :order, Integer
belongs_to :source, 'Person', :key => true
belongs_to :target, 'Person', :key => true
end
a = Person.new
b = Person.new
c = Person.new
a.friends = [b, c] # Keep in this order
a.friends == [b, c] # This should be true
a.friends != [c, b]
a.save
拯救人a应该在a和b之间建立友谊,订单价值= 1 以及 a 和 c 之间的第二个友谊,其订单值 = 2。
我在设置订单值时遇到了麻烦。据我所知,在保存 a 之前,友谊实际上并未创建,因此我无法在保存之前更新它们。保存后我无法更新它们,因为订单丢失了。
有什么想法吗?
I have a DataMapper many to many relationship, friends, that needs to be kept in the
order. Whats the best way to maintain the order? I placed an order property
in the join model, but cannot seem to figure out a good way to update it.
My code:
class Person
include DataMapper::Resource
property :id, Serial
property :name , String, :required => true
has n, :friendships, :child_key => [ :source_id ]
has n, :friends, self, :through => :friendships, :via => :target
end
class Friendship
include DataMapper::Resource
property :source_id, Integer, :key => true, :min => 1
property :target_id, Integer, :key => true, :min => 1
property :order, Integer
belongs_to :source, 'Person', :key => true
belongs_to :target, 'Person', :key => true
end
a = Person.new
b = Person.new
c = Person.new
a.friends = [b, c] # Keep in this order
a.friends == [b, c] # This should be true
a.friends != [c, b]
a.save
Saving person a should create a friendship between a and b with order value = 1
as well as a second friendship between a and c with order value = 2.
I've been having trouble setting the order values. From what I can tell, the friendships don't actually get created until a is saved, so I can't update them before saving. And I can't updated them after saving because the order is lost.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以这样做:
假设数据库后端中的顺序列自动递增,这应该会给您带来所需的效果。如果没有,那么您需要将类似的内容添加到您的 Friendship 模型中:
如果您关心这些友谊的顺序,那么您还需要在 Person 模型中执行此操作:
You could do this:
This should give you the desired effect, assuming that the order column in your database backend auto increments. If it doesn't then you need to add something like this to your Friendship model:
If you care about the order of these friendships then you also need to do this in the Person model: