1

I have two tables, nodes and terms.

The relevant fields in nodes are: nid (primary key) and value
In terms, they are: value, tid, and nid, where value and tid together are the primary key and nid is a foreign key referencing nodes.nid.

I want to add records to terms. I have the tid and nid, and the value I want to pull from the corresponding node - e.g. look up the value for a given nid in node and then put that as the value in terms.

A way to do this in SQL might be:

INSERT INTO terms(tid, nid, value)
values(mytid, mynid, (
    select value from nodes where nid=mynid
));

Could somebody help me do this with DataMapper?

class Node
    include DataMapper::Resource

    property :nid,    Serial,  :key => true
    property :value,  Integer

end


class Term
    include DataMapper::Resource

    property :tid,    Integer, :key => true

    # how do I define nid and value?
end

# and then what do I give to Term.new or Term.create and how?

If anyone could point me to a good tutorial of DataMapper as well, I'd appreciate it. I've been using their online docs, but I've found the situations I find myself in are rarely covered there.

hsiu
  • 21
  • 2
  • I found the doc's OK, but support on IRC was great. Check out the following question I had. The answer explained how to do relationships and query against them. http://stackoverflow.com/questions/2826439/beginning-with-datamapper-association-question –  Apr 05 '11 at 19:02

1 Answers1

1

From your description the models you're looking for should be setup like that:

class Node
  include DataMapper::Resource

  property :nid,    Serial
  property :value,  Integer
end

class Term
  include DataMapper::Resource

  property :tid,   Integer, :key => true
  property :value, Integer, :key => true

  belongs_to :node, :child_key => :nid
end

You can work with these models like that:

# create a node
node = Node.create(:value => 123)

# create a term and associate it with the node
term = Term.create(:tid => 321, :node => node, :value => node.value)
solnic
  • 5,733
  • 2
  • 23
  • 19
  • 1
    Thanks for your answer. Is this really the only way to do it? Because that's how I considered doing it in the first place, but I thought there might be a way, if I defined the models well, that I could do Term.create(:tid => 321, :nid=>999) and it would, internally, convert that to "lookup nid 999 using Node, then insert tid=321,nid=999,vid=whatever you found there". I can make a method within Term to do that and hide the details, but I thought that might be something DataMapper could handle with a well flushed-out model. Maybe that's asking a lot. – hsiu Apr 05 '11 at 21:31
  • You can set up a before save hook which would do self.value = node.value – solnic Apr 05 '11 at 23:22