我刚开始使用 Laravel,我收到以下错误:
未知列“updated_at”插入到 gebruikers(naam、wachtwoord、updated_at、created_at)
我知道错误来自迁移表时的时间戳列,但我没有使用 updated_at
字段。我曾经在学习 Laravel 教程时使用它,但现在我正在制作(或尝试制作)我自己的东西。即使我不使用时间戳,我也会收到此错误。我似乎找不到使用它的地方。这是代码:
控制器
public function created()
{
if (!User::isValidRegister(Input::all())) {
return Redirect::back()->withInput()->withErrors(User::$errors);
}
// Register the new user or whatever.
$user = new User;
$user->naam = Input::get('naam');
$user->wachtwoord = Hash::make(Input::get('password'));
$user->save();
return Redirect::to('/users');
}
路线
Route::get('created', 'UserController@created');
模型
public static $rules_register = [
'naam' => 'unique:gebruikers,naam'
];
public static $errors;
protected $table = 'gebruikers';
public static function isValidRegister($data)
{
$validation = Validator::make($data, static::$rules_register);
if ($validation->passes()) {
return true;
}
static::$errors = $validation->messages();
return false;
}
我一定是忘记了什么……我在这里做错了什么?
在模型中,编写以下代码;
public $timestamps = false;
这会奏效。
解释:默认情况下,laravel 会在你的表中期望 created_at 和 updated_at 列。通过将其设置为 false ,它将覆盖默认设置。
将时间戳设置为 false 意味着您将丢失 created_at 和 updated_at 而您可以在模型中设置这两个键。
情况1:
您有 created_at
列但没有 update_at 您可以在模型中简单地将 updated_at
设置为 false
class ABC extends Model {
const UPDATED_AT = null;
案例二:
您同时拥有 created_at
和 updated_at
列,但列名不同
你可以简单地做:
class ABC extends Model {
const CREATED_AT = 'name_of_created_at_column';
const UPDATED_AT = 'name_of_updated_at_column';
最后完全忽略时间戳:
class ABC extends Model {
public $timestamps = false;
}
链接到 laravel 文档 https://laravel.com/docs/9.x/eloquent#timestamps
亚历克斯和萨米尔的回答很好,但也许只是关于为什么需要放置的附加信息
public $timestamps = false;
官方Laravel page很好地解释了时间戳:
默认情况下,Eloquent 期望 created_at 和 updated_at 列存在于您的 >tables 中。如果您不希望 >Eloquent 自动管理这些列,请将模型上的 $timestamps 属性设置为 false。
对于使用 laravel 5 或更高版本的用户,必须使用 public 修饰符,否则会抛出异常
Access level to App\yourModelName::$timestamps must be
public (as in class Illuminate\Database\Eloquent\Model)
public $timestamps = false;
如果您仍然需要时间戳,但只是忘记在迁移中添加它们,将以下内容添加到迁移文件中也可以:
class AddUsersTable extends Migration
{
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->timestamps(); // <-- Add this to add created_at and updated_at
});
}
}
不要忘记之后重新运行迁移。
php artisan migrate:rollback
php artisan migrate
不定期副业成功案例分享
By default, Eloquent expects created_at and updated_at columns to exist on your tables. If you do not wish to have these columns automatically managed by Eloquent, set the $timestamps property on your model to false
$table->timestamps();
因此,在迁移中时间戳默认为关闭,但在模型中默认为开启。