SQLSTATE [HY000]尝试从下拉列表中选择并传递值时

问题描述 投票:0回答:2

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

我的数据库中的类别和帖子表是分开的,并且帖子中有一列category_id,它是类别表的外键。

我的帖子创建刀片为:

<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上的商店功能是:

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个类别相关联

php laravel laravel-5.8
2个回答
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()方法时,您需要指定哪些字段可进行质量分配。您可以通过将它们添加到模型的$fillable属性来执行此操作。

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

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

1
投票

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

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

在新帖子中添加类别ID。并且您需要确保该用户将选择类别

© www.soinside.com 2019 - 2024. All rights reserved.