【问题标题】:ERROR: Column not found: 1054 Unknown column 'updated_at' in 'field list'错误:未找到列:1054“字段列表”中的未知列“updated_at”
【发布时间】:2019-10-13 21:22:44
【问题描述】:

所以基本上错误表明我没有名为 updated_at 的列,但我知道我没有它,我不想拥有它。我的数据库表只有以下列:requester、user_requested、id、status。

这是我的模特

class Friendships extends Model
{
    protected $fillable = ['requester', 'user_requested', 'status'];
}

这是我的配置文件控制器

 public function sendRequest($id){
        return Auth::user()->addFriend($id);

  }

这是我的friendable.php


namespace App\Traits;
use App\Friendships;

trait Friendable{
    public function test(){
        return 'hi' ;
    }

    public function addFriend($id){
        $Friendship = Friendships::create([
                'requester' => $this->id,
                'user_requested' => $id
        ]);


        if($Friendship){
            return $Friendship;
        }
        return  'failed';
    }


}

它说方法 addFriend 没有找到,并且 create 显然不起作用,因为没有找到 id。

【问题讨论】:

  • 在模型中尝试public $timestamps = false; 并检查

标签: php html laravel


【解决方案1】:

默认情况下,Eloquent 期望 created_atupdated_at 列存在于您的表中。如果您不希望 Eloquent 自动管理这些列,请将模型上的 $timestamps 属性设置为 false

class Friendships extends Model
{
    public $timestamps = false;
    protected $fillable = ['requester', 'user_requested', 'status'];
}  

编辑

发射命令,

php artisan make:migration modify_friendships_table;

然后转到database/migrations生成的迁移文件

在该类中编写代码,

Schema::table('friendships', function (Blueprint $table) {
    $table->boolean("status")->default(0)->change();
});

保存上面的文件,然后在下面的命令中触发

php artisan migrate

现在检查它是否正常工作。

【讨论】:

  • 成功了,谢谢!但现在它显示此错误:一般错误:1364 字段“状态”没有默认值(SQL:插入friendshipsrequesteruser_requested)值(1、1))
  • 如果您想将status 设置为 null (如果未设置任何值),那么您必须创建新的迁移脚本来更改该列以在未设置任何值的情况下设置为 null。这是 doc 用于更改列。我对答案进行了更改。现在检查。
  • 但我的状态是布尔值
【解决方案2】:

Laravel 会自动尝试设置 created_atupdated_at 字段的值。强烈建议使用这些,但如果您不想这样做,可以在您的模型上禁用它们。

为此,只需将public $timestamps = false; 添加到模型中。例如:

class Friendships extends Model
{
    public $timestamps = false;
    protected $fillable = ['requester', 'user_requested', 'status'];
}

【讨论】:

  • 成功了,谢谢!但现在它显示此错误:General error: 1364 Field 'status' doesn't have a default value (SQL: insert into friends (requester, user_requested) values (1, 1)
猜你喜欢
  • 2013-05-26
  • 2021-10-24
  • 2021-12-03
  • 2019-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多