在freecodecamp.org教程之后,我在这里刷新我的Laravel技能(使用7.13.0版):https://www.youtube.com/watch?v=ImtZ5yENzgE&t=11889s(1:21:49至1:22:50)。当我开始使用 php artisan tinker 手动添加配置文件的任务时,就像我在前端所做的那样,它无法保存。该数据库是sqlite。
这是完全错误:
Illuminate / Database / QueryException,消息为'SQLSTATE [23000]: 违反完整性约束:19 NOT NULL约束失败: profiles.url(SQL:插入“个人资料”(“标题”,“说明”, “ user_id”,“ updated_at”,“ created_at”)值(酷标题, Description,1,2020-05-29 18:41:02,2020-05-29 18:41:02))'
我在database \ migrations文件夹中的 profiles_table.php 中的功能似乎正常。就是这样:
public function up()
{
Schema::create('profiles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->string('title')->nullable();
$table->text('description')->nullable();
$table->string('url')->nullable();
$table->timestamps();
$table->index('user_id');
});
}
Profile.php模型功能是:
public function user()
{
return $this->belongsTo(User::class);
}
User.php模型功能为:
public function profile()
{
return $this->hasOne(Profile::class);
}
因此,在终端中,输入 php artisan tinker 之后,我在无法保存之前填写了以下内容:
>>> $profile = new \App\Profile();
=> App\Profile {#3056}
>>> $profile->title = 'Cool Title';
=> "Cool Title"
>>> $profile->description = 'Description';
=> "Description"
>>> $profile->user_id = 1;
=> 1
>>> $profile->save();
编辑:这是控制器文件 ProfilesController.php ,如果它有助于解决问题:
<?php
namespace App\Http\Controllers;
use \App\User;
use Illuminate\Http\Request;
class ProfilesController extends Controller
{
public function index($user)
{
$user = User::find($user);
return view('home', [
'user' => $user,
]);
}
}
所有部分都正常,然后键入SAVE-显示上面的错误。因此,我无法继续显示手动制作的新配置文件。
我搜索了Google,并在这里寻找答案,例如this question和that question中的答案。它没有解决我的问题,我认为其他问题并不重要。
该如何解决?
向@mrhn表示感谢,添加一个新的空表并按照以下建议安装composer require doctrine/dbal
:https://stackoverflow.com/a/37533819/12952748。
答案 0 :(得分:2)
问题是您的数据库不允许列url
为空。您的代码很好,而且没有任何问题,您似乎之后可能已经运行了迁移并更改了列定义。
在Laravel中,迁移仅运行一次,并确保数据库在系统之间具有相同的结构。为了使该字段可为空,请进行新的迁移。
php artisan make:migration url_nullable
对于新的迁移文件,添加以下迁移。只是告诉迁移将url
更新为string
和nullable
。
Schema::table('profiles', function (Blueprint $table) {
$table->string('url')->nullable()->change();
});
运行之后,您的迁移和数据库应该是最新的。
php artisan migrate