SQLSTATE [HY000]:常规错误:1364字段“ author_id”没有默认值

我实际上是Laravel Framework的新手。一直试图发布到Mysql数据库,我的Author_id出现错误。


SQLSTATE [HY000]:常规错误:1364字段'author_id'没有默认值。


到处都检查过,但所有努力都证明是失败的


这是迁移


public function up()

{

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

        //$table->engine = “InnoDB”;


        $table->increments('id');

        $table->integer('author_id')->unsigned();

        $table->foreign('author_id')->unique()->references('id')->on('users')->onDelete('restrict');

        $table->string('title');

        $table->string('slug')->unique();

        $table->text('excerpt');

        $table->text('body');

        $table->unsignedInteger('user_id');

        $table->string('image')->nullable();   

        $table->timestamps();

    });




}

这是我的create.blade.php:


 <section class="content">

        <div class="row">

          <div class="col-xs-12">

            <div class="box">

              <div class="box-body">


              {!! Form::model($post, [

                    'method' => 'POST',

                    'url'  => 'backend/blog'

              ]) !!}  


             {{-- <form method="POST" action="{{ url('blog/store') }}" enctype="multipart/form-data">

                @csrf  --}}


                    <div class="form-group {{ $errors->has('title') ? 'has-error' : '' }}">

                        {!! Form::label('title') !!}

                        {!! Form::text('title', null, ['class' => 'form-control']) !!}


                        @if($errors->has('title'))

                        <span class="help-block">{{ $errors->first('title') }} </span>

                        @endif

                    </div>



                    <div class="form-group {{ $errors->has('slug') ? 'has-error' : '' }}">

                      {!! Form::label('slug') !!}

                      {!! Form::text('slug', null, ['class' => 'form-control'])!!}       

慕哥6287543
浏览 286回答 1
1回答

HUX布斯

例如,将Post与当前用户相关联(例如,在将Post保存到db的控制器方法内部)可以像以下操作:// controller methodpublic function savePost( Request $request ){&nbsp; &nbsp; $data = $request->validate([&nbsp; &nbsp; &nbsp; &nbsp; // your validation rules here..&nbsp; &nbsp; &nbsp; &nbsp; ]);&nbsp; &nbsp; $post = new Post(); // from Post model&nbsp; &nbsp; $post->fill($data);&nbsp; &nbsp; $post->author()->associate(\Auth::user()); // relate post to current user&nbsp; &nbsp; $post->save(); // save to db&nbsp; &nbsp; return view('whatever_your_view_is', []);}如果您需要更多信息,请发表评论在Post模型中进行以下更改:public function author(){&nbsp; &nbsp; return $this->belongsTo(User::Class, 'author_id'); // specify the column which stores the author in posts table}
打开App,查看更多内容
随时随地看视频慕课网APP