# Foreign Key in Seeders

**URL:** <https://discourse.cakephp.org/t/foreign-key-in-seeders/7534>\
**Category:** Need Help\
**Created:** [March 24, 2020, 4:30pm UTC](https://discourse.cakephp.org/t/foreign-key-in-seeders/7534 "2020-03-24T16:30:20Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![4yz4](https://avatars.discourse-cdn.com/v4/letter/4/dfb087/32.png) [@4yz4](https://discourse.cakephp.org/u/4yz4)\
**Post date:** [March 24, 2020, 4:30pm UTC](https://discourse.cakephp.org/t/foreign-key-in-seeders/7534/1 "2020-03-24T16:30:20Z")

</div>

I have a problem with the foreign key to generate random data, I already overflowed the documentation of the Seeders but there is no relationship with the foreign keys, I hope your help, thanks.

```
public function getDependencies(){
        return UsersTable::class;
}
public function run()
    {
        $faker = Faker\Factory::create();
        $data = [];
        $foreignKeys = $this->getDependencies()->fetchAll(['id']);

        for ($i=0; $i < 200 ; $i++) { 
            $data[] = [
                'title' => $faker->name(),
                'description' => $faker->text(),
                'url' => $faker->url(),
                'created' => date("Y-m-d H:i:s"),
                'modified' => date("Y-m-d H:i:s"),
                'user_id' => $foreignKeys[array_rand($foreignKeys)]
            ];
        }
        $table = $this->table('bookmarks');
        $table->insert($data)->save();
    }
```

---

<div class="post-metadata">

**Author:** ![vovo98er](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/vovo98er/32/1721_2.png) [@vovo98er](https://discourse.cakephp.org/u/vovo98er)\
**Post date:** [March 25, 2020, 1:40am UTC](https://discourse.cakephp.org/t/foreign-key-in-seeders/7534/2 "2020-03-25T01:40:18Z")

</div>

^^ You can try:

```
...  
'user_id' => $faker->randomElement($foreignKeys);
...

```

> **[fzaninotto/Faker](https://github.com/fzaninotto/Faker#fakerproviderbase)**
>
> Faker is a PHP library that generates fake data for you - fzaninotto/Faker
