我试图在应用程序中添加一个选择框,以便用户选择要分配给他的帖子的类别。
我的数据库中的Categories和Post表是分开的,并且Posts中有一列category_id,这是Categories表的外键。
我的帖子创建刀片为:
<div class="container">
<form method="POST" action="/posts">
{{csrf_field()}}
<div>
<label>Title</label>
<input type="text" name="title" required>
</div>
<div>
<label>Slug</label>
<input type="text" name="slug" required>
</div>
<div>
<label>Subtitle</label>
<input type="text" name="subtitle" required>
</div>
<div>
<label>Content</label>
<input type="text" name="content" required>
</div>
<div class="form-group">
<select class="form-control" name="categories_id">
@foreach($categories as $category)
<option value="{{$category->title}}">{{$category->title}}</option>
@endforeach
</select>
</div>
<div style="margin-top: 10px">
<input type="submit" value="Make Post">
</div>
</form>
</div>
我的Posts Controller上的store函数是:
public function store(Request $request)
{
$post = new Post();
$post->title = request('title');
$post->slug = request('slug');
$post->subtitle = request('subtitle');
$post->content = request('content');
$post->save();
return redirect('/posts');
}
创建函数是
public function create()
{
$categories = Category::all(['id','title']);
return view('posts.create',compact('categories',$categories));
}
最后是我的模特
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public $table = "posts";
}
当前,当我尝试选择一个选项时,我会得到一个
SQLSTATE [HY000]:常规错误:1364字段'category_id'没有默认值。
我不希望它为空。并且每个帖子至少应与1个类别相关联