SQLSTATE[HY000] 尝试 select 并从下拉列表中传递一个值时

SQLSTATE[HY000] When trying to select and pass a value from a dropdown

我正在尝试在我的应用程序中添加一个 select 框,以便用户选择要分配给他的 Post 的类别。

我的数据库中的类别和 Post table 是分开的,Post 中有一列 category_id 是类别 table.

我为 post 创建的 blade 是:

<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>

我的 Post 控制器上的存储功能是:

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]: General error: 1364 Field 'category_id' doesn't have a default value.

我不希望它为空。每个 post 应该至少与 1 个类别相关联

在您的 select 中,使用类别的 ID 而不是标题作为值。

<select class="form-control" name="category_id">
    @foreach($categories as $category)
        <option value="{{ $category->id }}">{{ $category->title }}</option>
    @endforeach
</select>

然后,在你的 store() 方法中,将该值传递给 posts create() 方法(或者你可以使用 $post = new Post() 并手动分配它们,它也可以工作,但是这有点短)。

这假定用户选择了一个类别 - 您似乎没有任何验证,因此您或许可以考虑使用验证器(参见 https://laravel.com/docs/6.x/validation)。

public function store(Request $request)
{
    $post = Post::create($request->only("title", "slug", "subtitle", "content", "category_id"));

    return redirect('/posts');
}

使用create()update()方法时,需要指定哪些字段是mass-assignable。您可以将它们添加到模型的 $fillable 属性 中。

class Post extends Model
{
    public $table = "posts";

    protected $fillable = ["title", "slug", "subtitle", "content", "category_id"];
}

store()方法中save()之前需要添加

$post->content = request('categories_id');

在新 post 中添加类别 ID。您需要确保该用户会选择类别