在数据库表中存储多个复选框值 拉拉维尔

到目前为止,我知道我需要将复选框值存储在数组中,如下所示:


<input name="thinking_traps[]" type="checkbox" value="1">

<input name="thinking_traps[]" type="checkbox" value="2">

<input name="thinking_traps[]" type="checkbox" value="3">

但是我不确定如何将这些值正确传递给控制器并将其添加到迁移表中?是否将每个值作为单独的列添加到数据库中?


在这里,我尝试添加它们,就像任何其他输入一样:


public function store(Request $request)

    {

        $this->validate($request, [

            'thought_entry' => 'required'

        ]);




        $entry = new ThoughtJournal;

        $entry->user_id = auth()->user()->id;

        $entry['entry_date'] = date('Y-m-d H:i');

        $entry->thought_entry = $request->input('thought_entry');

        $entry->emotions = $request->input('emotions');

        $entry->thinking_traps = $request->input('thinking_traps');

        $entry->balanced_thought = $request->input('balanced_thought')

        $entry->save();


        return redirect('/dashboard');

    }

public function up()

    {

        Schema::create('thoughtjournal', function (Blueprint $table) {

            $table->increments('entry_id');

            $table->integer('user_id');

            $table->date('entry_date');

            $table->mediumText('thought_entry');

            $table->

            $table->timestamps();

        });

    }


aluckdog
浏览 145回答 3
3回答

慕莱坞森

我在您的表迁移文件中没有看到thinking_traps型class ThoughtJournal{&nbsp; &nbsp;// Add it's type to casts as array&nbsp; &nbsp;public $casts = ['thinking_traps'=> 'array'];&nbsp; &nbsp;// Add it to fillables if you haven't&nbsp; &nbsp;public $fillable = ['thinking_traps',...];&nbsp; &nbsp;//...}存储其次,在您的存储方法中,当复选框中没有选择任何项目时,您需要将其设置为数组,如下所示&nbsp; &nbsp;...&nbsp; &nbsp;$entry->thinking_traps&nbsp; &nbsp; &nbsp;= $request->has('thinking_traps')&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ? $request->get('thinking_traps')&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; : [];作为预防措施,对于验证,您可以像这样进行验证:$this->validate($request, [&nbsp; &nbsp;'thinking_traps' => 'nullable|in:1,2,3' // your values]);迁移对于迁移,我没有看到您在那里设置了列,您可以像这样修改迁移文件:// You can have it as json$table->json('thinking_traps')->nullable();// or string$table->string('thinking_traps')->nullable();或者,如果您不想在 shell/cmd 中重新创建表,则可以创建一个单独的迁移文件,如下所示:artisanphp artisan make:migration add_thinking_traps_to_thoughtjournal_table --table=thoughtjournal此命令将单独添加一个迁移文件,并像往常一样添加该列,然后您可以添加该列。php artisan migrate如果可行,请告诉我们。

慕的地10843

不应在数据库中的一行中存储多个值。应单独存储它,以便对数据进行规范化。

Qyouu

发布值将是一个数组,即使您选中了一个复选框。$thinking_陷阱 = $request->输入(“thinking_traps”);$thinking_traps 将是一个数组 因此请尝试将数组值保存在单独的表中,作为具有外键的多行
打开App,查看更多内容
随时随地看视频慕课网APP