一对一DataMapper关联 [英] One-to-one DataMapper association

查看:87
本文介绍了一对一DataMapper关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是DataMapper的新手,我正在尝试为以下场景创建模型:

I'm very new to DataMapper, and I'm trying to create models for the following scenario:

我有许多用户(使用用户名,密码等),它们也可以是玩家或裁判,或者两者都可以(因此,不能选择单表继承").基本模型为:

I've got a number of users (with a user name, password etc.), who can also be players or referees or both (so Single Table Inheritance is not an option). The base models would be:

class User
  include DataMapper::Resource
  property :id, Serial
  # Other user properties go here  
end

class Player
  include DataMapper::Resource
  property :id, Serial
  # Other player properties go here
  # Some kind of association goes here
end

class Referee
  include DataMapper::Resource
  property :id, Serial
  # Other referee properties go here
  # Some kind of association goes here
end

DataMapper.finalize

不过,我不确定要添加到播放器和裁判中的哪种类型的关联.使用belongs_to :user,可以将多个玩家与同一用户关联,这在我的上下文中是没有意义的.用RDBMS术语来说,我想我想要的是对球员"和裁判员"表中外键的唯一约束.

I'm not sure, though, what kinds of associations to add to Player and Referee. With belongs_to :user, multiple players can be associated with the same user, which doesn't make sense in my context. In RDBMS terms I guess what I want is a unique constraint on the foreign key in the Players and Referees tables.

如何在DataMapper模型中完成此操作?我必须在验证中亲自执行检查吗?

How do I accomplish this in my DataMapper model? Do I have to perform the check myself in a validation?

推荐答案

您可以通过不同的方式进行此操作.这是一个选择:

There are different ways you could do this. Here's one option:

class User
  include DataMapper::Resource
  property :id, Serial
  # Other properties...
  has 1, :referee, :required => false
  has 1, :player, :required => false
end

class Referee
  include DataMapper::Resource
  # DON'T include "property :id, Serial" here
  # Other properties...
  belongs_to :user, :key => true
end
class Player
  include DataMapper::Resource
  # DON'T include "property :id, Serial" here
  # Other properties...
  belongs_to :user, :key => true
end

对裁判/球员模型采取行动,例如:

Act on the referee/player models like:

u = User.create(...)
u.referee = Referee.create(...)
u.player = Player.create(...)

u.player.kick_ball() # or whatever you want to call
u.player.homeruns
u.referee.flag_play() # or whatever.

查看是否可行.我没有实际测试过,但是应该很好.

See if this works. I haven't actually tested it but it should be good.

这篇关于一对一DataMapper关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆