【问题标题】:SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed: posts.user_idSQLSTATE [23000]:违反完整性约束:19 NOT NULL 约束失败:posts.user_id
【发布时间】:2021-06-10 13:29:22
【问题描述】:

我正在尝试创建一个创建页面,其中用户在表单中输入标题并选择图像,但是当我单击按钮添加新帖子时,我收到此错误:

SQLSTATE[23000]:违反完整性约束:19 NOT NULL 约束失败:posts.user_id(SQL:插入“posts”(“caption”、“image”、“updated_at”、“created_at”)值(asd, C:\xampp\tmp\phpB7DC.tmp, 2021-03-12 13:06:56, 2021-03-12 13:06:56))

我想告诉你我正在使用一个 sqlite 数据库。

邮政模式:

class Post extends Model
{
    protected $fillable = [
        'caption', 'image',
    ];

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

PostsController:

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

    public function store() {

        $data = request()->validate([
            'caption' => 'required',
            'image' => 'required|image',
        ]);

        \App\Post::create($data);
        dd(request()->all());
    }
}

迁移文件夹中我的表格帖子:

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');
        });
    }

【问题讨论】:

  • 您没有在帖子中添加 user_id。

标签: database laravel sqlite model-view-controller


【解决方案1】:

您不会在交易中发送 user_id 值

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('user_id'); // this value must be set
        $table->string('caption');
        $table->string('image');
        $table->timestamps();
        $table->index('user_id');
    });
}

在这部分

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

public function store() {

        $data = request()->validate([
            'caption' => 'required',
            'image' => 'required|image',
        ]);

        // In this section you must add user_id to data
        // For example
        $data['user_id'] = Auth::user()->id; 

        \App\Post::create($data);
        dd(request()->all());
    }
}

【讨论】:

  • 当您告诉我必须设置 user_id 时,您是什么意思?不是连接到用户id表的外键吗?然后我如何在 PostsController 中添加我的 $data 变量?
  • 在您的迁移文件中,user_id 不可为空。也就是说每次在表中创建新记录时都必须设置user_id;
【解决方案2】:

在您的迁移中,您没有编写此列 Nullable。

您需要在验证中添加post_id

$data = request()->validate([
        'caption' => 'required',
        'image' => 'required|image',
        'post_id' => 'required|int'
    ]);

【讨论】:

    猜你喜欢
    • 2018-03-20
    • 2021-03-24
    • 1970-01-01
    • 2020-01-28
    • 2020-12-28
    • 2021-01-26
    • 2020-09-17
    • 2014-08-18
    相关资源
    最近更新 更多