# Foreignkey malformed

**URL:** <https://discourse.cakephp.org/t/foreignkey-malformed/12219>\
**Category:** Uncategorized\
**Created:** [August 31, 2024, 3:29pm UTC](https://discourse.cakephp.org/t/foreignkey-malformed/12219 "2024-08-31T15:29:28Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![ClaudioGS](https://avatars.discourse-cdn.com/v4/letter/c/b5ac83/32.png) [@ClaudioGS](https://discourse.cakephp.org/u/ClaudioGS)\
**Post date:** [August 31, 2024, 3:29pm UTC](https://discourse.cakephp.org/t/foreignkey-malformed/12219/1 "2024-08-31T15:29:28Z")

</div>

I have 2 foreign keys, one works and the other gives a malformed error  
1.-

```auto
public function change(): void
    {
        $refTable = $this->table('bitacora')
            ->addForeignKey('id_bitacora', 'comunidades', 'id_comunidad', ['delete'=> 'CASCADE', 'update'=> 'CASCADE'])
            ->save();
    }

```

In the botacora table the id has been changed to id\_bitacora as follows

```auto
$bitacora = $this->table('bitacora',['id' => false, 'primary_key'=> ['id_bitacora']]);
        $bitacora->addColumn('id_bitacora', 'integer', ['null' => false])

```

2.- This doesn’t work and gives an error:

```auto
public function change(): void
    {
        $refTable = $this->table('admins')
            ->addForeignKey('id', 'comunidades', 'id_comunidad', ['delete'=> 'CASCADE', 'update'=> 'CASCADE'])
            ->save();
    }

```

```auto
PDOException: SQLSTATE[HY000]: General error: 1005 Can't create table `servpcspa_syscon`.`admins` (errno: 150 "
Foreign key constraint is incorrectly formed") in /home/servpcspa/web/servpcspa.com/public_html/vendor/robmorga
n/phinx/src/Phinx/Db/Adapter/PdoAdapter.php:203

```

---

<div class="post-metadata">

**Author:** ![jmcd73](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/jmcd73/32/481_2.png) [@jmcd73](https://discourse.cakephp.org/u/jmcd73)\
**Post date:** [August 31, 2024, 10:03pm UTC](https://discourse.cakephp.org/t/foreignkey-malformed/12219/2 "2024-08-31T22:03:30Z")

</div>

Sorry I’m not too familiar with FK’s but what might be useful to work to a resolution is running the examples from the docs at [Writing Migrations - 0.16](https://book.cakephp.org/phinx/0/en/migrations.html#working-with-foreign-keys) in a test database.

If you install MySQL Workbench and look at the resulting FK’s in the GUI you can then work back to a working migration by comparing the examples in the docs with what they appear as in MySQL Workbench.
