“ SQLSTATE [HY000]:一般错误:1364字段'user_id'没有默认值(SQL:插入

时间:2018-07-29 13:12:49

标签: php mysql laravel

使用laravel时出现此错误。我正在尝试保存图书数据,并使用user_id保存其所有者用户。抱歉,问题格式。

public function store(InfoValid $request)
{
    $request->validated();
    $user = Auth::user()->books()->create($request->except('_token'));
    //dd($user ->user_id);
    Book::create($request->except('_token'));
    redirect("/books");
}
}
  

“ SQLSTATE [HY000]:常规错误:1364字段'user_id'没有默认值(SQL:插入booksnamepage,{{1 }},ISBNpricepublished_atupdated_at)值))◀“

在我的User类中,我有:

created_at

在我的“图书”课程中:

public function books(){
    return $this->hasMany(Book::class);
}

在我的书本表中:

protected $fillable = [
    "name" , "page" , "ISBN" , "price" , "published_at"
];

public function user()
{
return $this ->belongsTo(User::class);
}

当我dd()user_id(我已经评论过)时,它给了我user_id,但是我不知道为什么我要面对这个错误

1 个答案:

答案 0 :(得分:0)

Auth::user()->books()->create($request->except('_token'));

将自动在user_id实体中设置Book

但是这里

Book::create($request->except('_token'));

user_id不会被设置。因此,laravel将尝试插入没有user_id的书(这是必需的),而MySQL会抱怨。但是您也不需要第二行,因为这本书已经与第一行一起保存了。