php - SQLSTATE [23000]:违反完整性约束:1048 列 'category_id' 不能为空
问题描述
我想在发布/创建表单中创建一个带有category_id 作为下拉列表的帖子,但我得到一个SQLSTATE [23000]:完整性约束违规:1048 列'category_id'不能为空(SQL :插入posts
(,,,,,, )...title
body
category_id
author_id
updated_at
created_at
我需要一些帮助来找出导致此问题的原因,这就是我到目前为止所拥有的...
创建.blade.php
@extends('layouts.app')
@section('content')
<div class="container">
<h1>Create Post</h1>
<div class="row post_row">
{!! Form::open(['action' => 'PostsController@store', 'method' => 'POST', 'class' => 'form']) !!}
<div class="col-md-8">
<div class'form-group'>
{{ Form::label('title', 'Title')}}
{{ Form::text('title', '', ['class' => 'form-control', 'placeholder' => 'Title'])}}
</div>
</div>
<div class="col-md-4">
<div class'form-group'>
{{ Form::label('categories_id', 'Category :')}}
<select class='form-control' title="category_id">
@foreach ($categories as $category => $value)
<option value="{{$value->id }}">{{ $value->title }}</option>
@endforeach
</select>
</div>
</div>
</div>
<div class="row post_row">
<div class="col-md-8">
<div class'form-group'>
{{ Form::label('body', 'Body')}}
{{ Form::textarea('body', '', ['id' => 'article-ckeditor', 'class' => 'form-control space', 'placeholder' => 'Body Text'])}}
</div>
</div>
</div>
<div class'form-group' style="padding-top: 20px">
{{Form::submit('Submit', ['class'=>'btn btn-primary'])}}
{!! Form::close() !!}
</div>
</div>
@endsection
PostController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
use App\Category;
class PostsController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
protected $limit = 3;
public function create()
{
$posts = Post::all();
$categories = Category::all();
return view('posts.create')->with(['posts' => $posts, 'categories' => $categories]);
}
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required|max:255',
'body' => 'required'
]);
//create Post
$post = new Post;
$post->title = $request->input('title');
$post->body = $request->input('body');
$post->category_id = $request->input('category_id');
$post->author_id = auth()->user()->id;
$post->save();
return redirect('/posts')->with('success', 'Your post created created successfully');
}
public function update(Request $request, $id)
{
$updated = Category::findorFail($id);
$categories = $request->all();
$category_id = $request->get('category_id');
$updated->fill($categories)->save();
return redirect('/dashboard')->with('success', 'Your post created updated successfully');
}
Post.php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
use GrahamCampbell\Markdown\Facades\Markdown;
class Post extends Model
{
//Table Name
protected $table = 'posts';
// Primary Key
public $primaryKey = 'id';
// Timestamps
public $timestamps = true;
protected $fillable = [
'title',
'excerpt',
'body',
'categery_id',
'image',
];
protected $dates = ['published_at'];
public function author()
{
return $this->belongsTo(User::class);
}
public function category()
{
return $this->belongsTo(Category::class);
}
public function getImageUrlAttribute($value)
{
$imageUrl = "";
if( ! is_null($this->image))
{
$imagePath = public_path() . "/img/" . $this->image;
if(file_exists($imagePath)) $imageUrl = asset("img/" . $this->image);
}
return $imageUrl;
}
public function getDateAttribute()
{
return is_null($this->published_at) ? '' : $this->published_at->diffForHumans();
}
public function getExcerptHtmlAttribute()
{
return $this->excerpt ? Markdown::convertToHtml(e($this->excerpt)) : NULL;
}
public function getBodyHtmlAttribute()
{
return $this->body ? Markdown::convertToHtml(e($this->body)) : NULL;
}
public function scopeLatestFirst($query)
{
return $query->orderBy('published_at', 'desc');
}
public function scopePublished($query)
{
return $query->where('published_at', '<=', Carbon::now());
}
}
分类.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $table = 'categories';
protected $fillable = [
'title',
'categery_id'
];
public function posts()
{
return $this->hasMany(Post::class);
}
public function getRouteKeyName()
{
return 'slug';
}
}
创建PostsTable.php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('author_id')->unsigned();
$table->foreign('author_id')->references('id')->on('users')->onDelete('restrict');
$table->integer('category_id')->unsigned();
$table->foreign('category_id')->references('id')->on('categories')->onDelete('restrict');
$table->string('title');
$table->string('slug')->unique();
$table->text('excerpt');
$table->mediumText('body');
$table->string('image')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
所以这就是我到目前为止所拥有的,有人知道我为什么会遇到这个问题吗?
解决方案
认为问题出现是因为类别 ID 在 CreatePostsTable 迁移中不可为空。你可以像这样使它可以为空。
$table->integer('category_id')->nullable()->unsigned();
推荐阅读
- ubuntu-16.04 - 更新 Ubuntu 更新 python 版本?
- image - 如何使图像颤动中的形状低于形状
- php - 使用php进行分页?
- python - 是否可以在 Openlayers 上旋转图像层?
- bash - 如何将多行输出解析为单独的变量
- javascript - OpenWeatherMap API 返回“未定义”
- c++ - 如何混淆或删除二进制文件中的导出名称
- javascript - 根据数字增量选中或取消选中复选框?(仅在纯 javascript 中)
- python - 为什么我在 python 中的 Boolean def 为空时返回 True?
- python - 如果我安装了 python 3.8,为什么我缺少 python39.dll 文件。7