我有postqs和users表。用户id是postqs表中的外键。我有一个表格,在我提交表格后,所有的数据都正确地保存在数据库中。但它没有指向索引页,而是显示以下错误:
SQLSTATE[HY000]:一般错误:1364字段“user_id”没有
默认值(SQL:insert intoPostqsquestiondescription
solutionimagetagsupdated_atcreated_at)值(hh,
bb,bb,images.bmp.jpg,bb,2017-09-20 08:14:32,2017-09-20
08:14:32)
我怎么解决?
存储控制器功能:

public function store(Request $request)
{
    $this->validate($request, [
        'question' => 'required',
        'description' => 'required',
        'tags' => 'required',

    ]);

    $user = auth()->user();
    $user->postqs()->create($request->all() );

    $input = $request->all();
    $tags = explode(",", $request->tags);

    $postqs = Postqs::create($input);
    $postqs->tag($tags);

    return redirect()->route('postqs.index')
                    ->with('success','Your question created successfully');

索引控制器功能:
   $postqs=Postqs::whereHas('user')->get();
    return view('postqs.index',compact('postqs','users'));

postqs模型:
    protected $fillable =
    ['question','description','solution','image','tags','user_id'];

    public function user(){
    return $this->belongsTo("App\User"); }

用户型号:
    public function postqs(){
     return $this->hasMany("App\Postqs");
    }

最佳答案

表中的字段user_id不可为空,您试图保存没有user_id的post,或者可能是user_id is not passed by request。
试试这个:

$this->validate($request, [
    'question' => 'required',
    'description' => 'required',
    'tags' => 'required',

]);

$user = auth()->user();
$data = $request->all();
$data['user_id']=$user->id;
$user->postqs()->create($data);
$tags = explode(",", $request->tags);

$postqs = Postqs::create($data);
//$postqs->tag($tags);
$postqs->tag()->save($tags);

return redirect()->route('postqs.index')
                ->with('success','Your question created successfully');

07-26 02:05