【问题标题】:Laravel db:seed attempts to seed wrong tableLaravel db:seed 尝试播种错误的表
【发布时间】:2019-11-14 05:39:15
【问题描述】:

我在用户和 nextOfKin 模型之间建立了这样的关系

用户.php

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

NextOfKin.php

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

我已经使用迁移创建了usersnext_of_kins 表,并希望使用数据库种子向表中添加数据。当我运行我的UsersTableSeeder

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

返回错误

Illuminate\Database\QueryException:SQLSTATE[42P01]:未定义表:7 错误:关系“next_of_kin”不存在 第 1 行:插入 "next_of_kin" ("user_id", "firstname", "lastname... ^ (SQL: 插入 "next_of_kin" ("user_id", "firstname", "lastname", "relationship", "address", "state", "country", "updated_at", "created_at") 值 (1,威利,麦卡洛,家庭,3334 B ridget Cliffs, Michigan, Micronesia, 2019-07-03 13:35:48, 2019-07-03 13:35:48) 返回“id”)

为什么迁移尝试插入next_of_kin 而不是next_of_kins 表?用户表播种成功。如何解决这个问题?

【问题讨论】:

  • 你能展示 NextOfKin 的模型类吗?

标签: php postgresql laravel-5.8


【解决方案1】:

在模型中,可以指定使用什么表:

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

【讨论】:

  • 当 Laravel 无法根据模型名称和复数形式确定要使用的正确表名时,这是必要的。由于kin 是复数形式,Laravel 尝试使用的表是next_of_kin
猜你喜欢
  • 2021-09-07
  • 2014-08-26
  • 2014-12-08
  • 2014-11-26
  • 1970-01-01
  • 2014-07-28
  • 1970-01-01
  • 2019-09-12
  • 2019-04-06
相关资源
最近更新 更多