为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
慕哥6287543 2021-04-26 14:58:23
我实际上是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'])!!}       
查看完整描述

1 回答

?
HUX布斯

TA贡献1876条经验 获得超6个赞

例如,将Post与当前用户相关联(例如,在将Post保存到db的控制器方法内部)可以像以下操作:


// controller method

public function savePost( Request $request )

{

    $data = $request->validate([

        // your validation rules here..

        ]);

    $post = new Post(); // from Post model

    $post->fill($data);

    $post->author()->associate(\Auth::user()); // relate post to current user

    $post->save(); // save to db

    return view('whatever_your_view_is', []);

}

如果您需要更多信息,请发表评论


在Post模型中进行以下更改:


public function author()

{

    return $this->belongsTo(User::Class, 'author_id'); // specify the column which stores the author in posts table

}


查看完整回答
反对 回复 2021-05-07
  • 1 回答
  • 0 关注
  • 285 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信