Mena
Mena

Reputation: 2049

Laravel db:seed attempts to seed wrong table

I have a relationship between a user & nextOfKin model set up like this

User.php

public function nextOfKin()
{
    return $this->hasOne(NextOfKin::class, 'user_id');
}

NextOfKin.php

public function user()
{
    return $this->belongsTo(User::class);
}

I have created the users & next_of_kins tables using migration and want to add data to the table using database seeding. When I run my UsersTableSeeder

public function run()
{
    factory(App\User::class)->create()->each(function ($user) {
        $user->nextOfKin()->save(factory(App\NextOfKin::class)->make());
    });
}

it returns an error

Illuminate\Database\QueryException : SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "next_of_kin" does not exist LINE 1: insert into "next_of_kin" ("user_id", "firstname", "lastname... ^ (SQL: insert into "next_of_kin" ("user_id", "firstname", "lastname", "relationship", "address", "state", "country", "updated_at", "created_at") values (1, Willie, McCullough, family, 3334 B ridget Cliffs, Michigan, Micronesia, 2019-07-03 13:35:48, 2019-07-03 13:35:48) returning "id")

Why is the migration trying to insert into next_of_kin instead of next_of_kins table? The users table seeding is successful. How can this be fixed?

Upvotes: 1

Views: 538

Answers (1)

warbio
warbio

Reputation: 466

In the model, you can specify what table to use:

class NextOfKin extends Model
{
    protected $table= 'next_of_kins'; 
    ...
}

Upvotes: 1

Related Questions