ryanprayogo
ryanprayogo

Reputation: 11837

Grails GORM mapping FK that is not the PK of the other table

How do I map a GORM association where the foreign key is not a PK of the other table?

I have the following schema:

CREATE TABLE `supplier` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `partner_id` int(11) NOT NULL,
  `supplier_id` int(11) NOT NULL
  PRIMARY KEY (`id`)
)

CREATE TABLE `ad` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `partner_id` int(11) NOT NULL,
  `supplier_id` int(11) NOT NULL,
  `ad_id` varchar(30) NOT NULL,
  `ad_details` text NOT NULL
  PRIMARY KEY (`id`)
)

The FK relationship is between ad.supplier_id and supplier.supplier_id (NOT supplier.id).


EDIT: The answer by @tim_yates below seems to be partially working.

Since supplier.supplier_id is not the PK of the supplier table, therefore it is possible for supplier.supplier_id to be duplicated.

In fact, the key of the supplier table is the tuple (supplier.supplier_id, supplier.partner_id). How do I model this constraint?

Upvotes: 1

Views: 287

Answers (1)

tim_yates
tim_yates

Reputation: 171184

This similar question seems to show you should be able to add (using advanced Gorm Mapping):

  class Ad {
    Partner partner
    Supplier supplier
    String details

    static mapping = {
      supplier column:'supplier_id'
      details type:"text"
    }
  }

Though I've not tested this...

Upvotes: 1

Related Questions