gpt4 book ai didi

php - 违反完整性约束 : 19 NOT NULL constraint failed for something not in migration table

转载 作者:行者123 更新时间:2023-12-03 01:15:59 24 4
gpt4 key购买 nike

使用 Laravel 5.8.31 我似乎遇到了表中不应该为空的内容的完整性约束冲突。问题是它告诉我迁移文件中的 posts.title 不应该为空,但该变量甚至不在迁移表中。

SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint >failed: posts.title (SQL: insert into "posts" ("caption", "image", "user_id", >"updated_at", "created_at") values (kjhgj, C:\xampp\tmp\phpE3B7.tmp, 1, 2019->08-14 07:14:03, 2019-08-14 07:14:03))

我正在尝试学习 Laravel,并且一直在关注这个 YouTube 教程 https://www.youtube.com/watch?v=ImtZ5yENzgE

从浏览器获得的错误页面中,我可以看到错误是在 PostsController.php 中引发的。

我到达了 2:04:00,但遇到了这个问题。我读过这里提出和回答的许多其他问题,但没有运气。

发布迁移文件

class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->string('caption');
$table->string('image');
$table->timestamps();
$table->index('user_id');
// THERE IS NO 'title' entry.
});
}

帖子模型文件

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
//Tutorial uses guarded rather than fillable
protected $guarded = [];

public function user(){
return $this->belongsTo(User::class);
}
}

帖子 Controller 文件

class PostsController extends Controller
{
public function create()
{
return view('posts.create');
}

public function store()
{
$data = request()->validate([
'caption' => 'required',
'image' => ['required','image'],
]);

auth()->user()->posts()->create($data); //ERROR IS THROWN HERE


dd(request()->all());
}
}

我有一个页面,用户可以在其中输入标题并上传文件。无需任何验证,我就可以 dd(request()->all()); 查看标题和文件是否已收到。但是,当我在 Controller 文件中添加验证和 auth() 行时,我发现“posts.title”违反了完整性约束

我希望将标题和图像添加到数据库中。

第一次发帖,因为我通常都能找到答案,但这次我卡住了。

编辑:这是错误: Error Image

已解决

@Vipertecpro 能够解决我的问题。我必须运行以下两个命令:php artisan migrate:refresh --seed 然后 php artisan optimize:clear

@Don'tPanic 在本文的评论中解释了这些命令为何有效。

最佳答案

要允许 Laravel 在数据库中进行大量插入或更新,您必须在模型中声明 $fillable 变量。

就您而言:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
//Tutorial uses guarded rather than fillable
//protected $guarded = []; // If you use $fillable do not use $guarded

// HERE
protected $fillable = ['user_id', 'caption', 'image'];

public function user(){
return $this->belongsTo(User::class);
}
}

如果你不这样做,Laravel 会尝试将数组的所有数据插入数据库表中。

关于php - 违反完整性约束 : 19 NOT NULL constraint failed for something not in migration table,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57490585/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com