# Combine relation with different foreign keys

**URL:** <https://discourse.rom-rb.org/t/combine-relation-with-different-foreign-keys/196>\
**Category:** Issues\
**Created:** [December 2, 2017, 9:55am UTC](https://discourse.rom-rb.org/t/combine-relation-with-different-foreign-keys/196 "2017-12-02T09:55:16Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![andriy-baran](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.rom-rb.org/andriy-baran/32/120_2.png) [@andriy-baran](https://discourse.rom-rb.org/u/andriy-baran)\
**Post date:** [December 2, 2017, 9:55am UTC](https://discourse.rom-rb.org/t/combine-relation-with-different-foreign-keys/196/1 "2017-12-02T09:55:16Z")

</div>

I have a code like this

```ruby
module Relations
  class Messages < ROM::Relation[:sql]
    schema(:messages, infer: true) do
      attribute :id, Types::Int
      attribute :sender_id, Types::ForeignKey(:users)
      attribute :recipient_id, Types::ForeignKey(:users)

      associations do
        belongs_to :users, as: :sender, combine_key: :sender_id
        belongs_to :users, as: :recipient, combine_key: :recipient_id
      end

      primary_key :id
    end
  end
end

```

```ruby
module Relations
  class Users < ROM::Relation[:sql]
    schema(:users) do
      attribute :id, Types::Int
      attribute :login, Types::String

      associations do
        has_many :messages
      end

      primary_key :id
    end
  end
end

```

When I want to combine `sender` and `recipient` of a message

```ruby
repo.messages.combine(:sender, :recipient).by_pk(message.id).one
=> #<ROM::Struct::Message id=37 sender_id=1 recipient_id=2 body="first message" opened=false sender=#<ROM::Struct::Sender id=1 login="bob"> recipient=#<ROM::Struct::Recipient id=1 login="bob">>

```

I want recipient to be a correct user record

---

<div class="post-metadata">

**Author:** ![solnic](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.rom-rb.org/solnic/32/279_2.png) [@solnic](https://discourse.rom-rb.org/u/solnic)\
**Post date:** [December 5, 2017, 4:49pm UTC](https://discourse.rom-rb.org/t/combine-relation-with-different-foreign-keys/196/2 "2017-12-05T16:49:17Z")

</div>

Try changing `combine_key` settings to `foreign_key`, because that’s what it needs in order to figure out how to fetch associated records. `combine_key` is used to merge data in memory, in most common scenarios they are the same as fks, but conceptually they are different.
