更新:问题解决了!
我正在按照 freecodecamp.org 教程刷新我的Laravel技能(使用版本7.13.0(,在这里:https://www.youtube.com/watch?v=ImtZ5yENzgE&t=11889s(1:21:49至1:22:50(。当我开始使用php artisan 修补匠手动添加配置文件时,就像我在前端所做的那样,它无法保存。数据库是sqlite。
这是完整的错误:
Illuminate/Database/QueryException 与消息 'SQLSTATE[23000]: 完整性约束冲突:19 NOT NULL 约束失败: profiles.url (SQL:插入到"profiles"("title","description", "user_id"、"updated_at"、"created_at"(值(酷标题, 描述, 1, 2020-05-29 18:41:02, 2020-05-29 18:41:02(('
我在数据库\迁移文件夹中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');
});
}
配置文件.php模型函数为:
public function user()
{
return $this->belongsTo(User::class);
}
用户.php模型函数为:
public function profile()
{
return $this->hasOne(Profile::class);
}
所以,在终端中,在输入php工匠修补匠后,我在它无法保存之前填写了以下内容:
>>> $profile = new AppProfile();
=> AppProfile {#3056}
>>> $profile->title = 'Cool Title';
=> "Cool Title"
>>> $profile->description = 'Description';
=> "Description"
>>> $profile->user_id = 1;
=> 1
>>> $profile->save();
编辑:这是控制器文件ProfilesController.php,如果它有助于解决问题:
<?php
namespace AppHttpControllers;
use AppUser;
use IlluminateHttpRequest;
class ProfilesController extends Controller
{
public function index($user)
{
$user = User::find($user);
return view('home', [
'user' => $user,
]);
}
}
所有部分都正常,在我输入 SAVE 后 - 它显示了上面的错误。因此,我无法继续显示手动制作的新配置文件。
我搜索了谷歌并在这里寻找答案,就像这个问题和那个问题一样。它没有解决我的问题,我认为其他问题也不那么相关。
我应该怎么做才能修复它?
溶液
坦克要@mrhn,添加新的空表+安装composer require doctrine/dbal
,建议如下:https://stackoverflow.com/a/37533819/12952748。
问题是您的数据库不允许列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