【问题标题】:Column not found: 1054 Unknown column in 'field list' [closed]未找到列:1054“字段列表”中的未知列[关闭]
【发布时间】:2021-12-06 14:19:29
【问题描述】:

我不知道为什么我总是看到以下错误:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'ec_svdiscount_services.sv_discount_id' in 'field list'

我已经编辑了我的数据库并通过以下方式清除了所有缓存:

php artisan cache:clear
php artisan config:clear
php artisan route:clear
php artisan view:clear
php artisan clear-compiled
composer dumpautoload

所有这些都是为了删除 sv_discount_id 的所有记录,我的项目中不再使用该记录。我更应该拥有我在控制器、模型、存储库和所有相关内容中创建的 svdiscount_id。请问我做错了什么?如何阻止 sv_discount_id 出现。

【问题讨论】:

  • 如果您使用的是 linux 或 Mac,您可以从项目根目录尝试 grep -R sv_discount_id * | egrep -v storage 以查找该字段的任何用途。
  • @aynber 我使用 mac,我的客户端使用共享主机。当我使用你分享的命令时,我什么也得不到。
  • 你的模型类有名称SvDiscount吗?
  • @N69S 是的……我用那个名字做错了什么???
  • @Urget laravel 从类名中推导出外键以简化关系声明。您只需要调整使用字段svdiscount_id 而不是sv_discount_id 的关系。如果您的错误不是来自关系,那么您需要添加更多详细信息,说明您究竟在哪里得到了该错误。 (更具体的调试细节)

标签: php laravel has-many belongs-to


【解决方案1】:

当你的模型名是SvDiscount::class,当在关系中使用时,laravel 会从类名中推导出外键。

例如:

Class product 
{
    public function discount()
    {
        return $this->belongsTo(SvDiscount::class);
    }
}

在代码中使用这种关系时,laravel 会推断出products 表中存在的外键名为sv_discount_id。

一个简单的解决方案是将这些字段重命名为sv_discount_id。

另一种解决方案是在关系(documentation) 中指定外键:

Class product 
{
    public function discount()
    {
        return $this->belongsTo(SvDiscount::class, 'svdiscount_id');
    }
}

【讨论】:

  • 绝对正确!解决了我的问题。非常感谢@N69S
猜你喜欢
  • 2013-05-26
  • 2021-10-24
  • 2021-12-03
  • 2019-01-25
  • 1970-01-01
  • 1970-01-01
  • 2017-08-09
  • 2020-11-23
  • 1970-01-01
相关资源
最近更新 更多