# Foreign keys convention in CakePHP

**URL:** <https://discourse.cakephp.org/t/foreign-keys-convention-in-cakephp/3224>\
**Category:** Need Help\
**Created:** [September 18, 2017, 6:01pm UTC](https://discourse.cakephp.org/t/foreign-keys-convention-in-cakephp/3224 "2017-09-18T18:01:20Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Cupcake](https://avatars.discourse-cdn.com/v4/letter/c/d6d6ee/32.png) [@Cupcake](https://discourse.cakephp.org/u/Cupcake)\
**Post date:** [September 18, 2017, 6:01pm UTC](https://discourse.cakephp.org/t/foreign-keys-convention-in-cakephp/3224/1 "2017-09-18T18:01:20Z")

</div>

Hi there,

All foreign keys in a database must have an unique name. If I have three relations with a user then the names of the foreign keys must be different in the database  
In cakephp is by convention the name of the foreign key to the same table always the same. So fk name to Users is by convention user\_id. I can use this name only once in the database design as foreign key.  
Am I missing something or do I have to rename the foreign key in the Associations in cakephp?

I finally got the belongstomany working and saving associations is fine now. Now i need a second association to the same table but cannot use the same fk name user\_id. Why does cakephp not use the name of the foreign key as used in the database?

---

<div class="post-metadata">

**Author:** ![Diego](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/diego/32/296_2.png) [@Diego](https://discourse.cakephp.org/u/Diego)\
**Post date:** [September 18, 2017, 8:57pm UTC](https://discourse.cakephp.org/t/foreign-keys-convention-in-cakephp/3224/2 "2017-09-18T20:57:31Z")

</div>

if you are not using the cake convention just rename the key in table model,  
example 2 relations with same user model

```
    $this->belongsTo('Buyers', [
        'className' => 'Users',
         'foreignKey' => 'my_buyer_name_pk_id',
        'propertyName' => 'buyer'
    ]);
    
    
    $this->belongsTo('Sellers', [
        'className' => 'Users',
        'foreignKey' => 'my_seller_name_pk_id',
        'propertyName' => 'seller'
    ]);
```

---

<div class="post-metadata">

**Author:** ![Cupcake](https://avatars.discourse-cdn.com/v4/letter/c/d6d6ee/32.png) [@Cupcake](https://discourse.cakephp.org/u/Cupcake)\
**Post date:** [September 18, 2017, 9:06pm UTC](https://discourse.cakephp.org/t/foreign-keys-convention-in-cakephp/3224/3 "2017-09-18T21:06:16Z")

</div>

Thank you Diego, exactly what I thought. I guess it is the only way to use one table in two associations in cakephp.
