我正在尝试使用 VueJs 将数据存储到数据库中,并且不断收到500错误
这是我的代码:
export default {
props: ['post_id','user_id'],
data: function () {
return {
body:'',
user_name : '',
}
},
和方法在这里:
methods: {
loadComments() {
// axios.get("../api/comment").then(({ data })=>(this.comments - data.data)
axios.get("../api/comment").then((response) => (this.comments = response.data.data)
// response => this.comments = response.data
);
},
create() {
axios.post('../api/comment',{body:this.body});
},
这是我的表单的一部分:
<form @submit.prevent="create()" id="myForm" class="m-form m-form--fit m-form--label-align-right m-form--group-seperator-dashed">
<div class="form-group m-form__group row">
<div class="col-lg-6">
<label>name</label>
<input type="text" placeholder="insert name" name="body" class="form-control m-input" v-model="body">
</div>
<div class="col-lg-6">
<label>email</label>
<input type="text" placeholder="email" name="title" class="form-control m-input">
</div>
</div>
和api laravel的路线:
Route::resource('comment','CommentController');
最后是我在laravel中得到的日志错误:
[2019-03-25 07:07:08]本地。错误:SQLSTATE [HY000]:一般错误:1364字段“ body”没有默认值(SQL:插入
comments
(updated_at
,created_at
)值(2019-03-25 07:07:08,2019-03-25 07:07:08)){“ exception”:“ [object](Illuminate \ Database \ QueryException(代码:HY000):SQLSTATE [HY000]:常规错误:1364字段“ body”没有默认值(SQL:插入comments
(updated_at
,created_at
)值(2019-03-25 07:07:08,2019-03-25 07:07:08))在C:\ wamp \ www \ jabama3 \ vendor \ laravel \ framework \ src \ Illuminate \ Database \ Connection。 php:664,PDOException(代码:HY000):SQLSTATE [HY000]:常规错误:1364字段'body'在C:\ wamp \ www \ jabama3 \ vendor \ laravel \ framework \ src \ Illuminate中没有默认值\ Database \ Connection.php:458)
我知道我的表单没有发送数据,而laravel需要数据,但是我不知道我做错了哪一部分。
在这里编辑是我的存储方法:
public function store(Request $request)
{
Comment::create($request->all());
return (['message' => 'succes']);
}
这是我的表结构:
Schema::create('comments', function (Blueprint $table) {
$table->bigIncrements('id');
$table->longText('body');
$table->integer('user_id')->nullable();
$table->string('user_email')->nullable();
$table->string('user_name');
$table->integer('status')->default('0');
$table->integer('post_id');
$table->timestamps();
});
答案 0 :(得分:1)
这是因为在向表中插入数据时您的身体是空的。
原因是您正在使用创建用于插入数据的方法。
并且Create方法需要protected $fillable = ['field1','field2',...]
数组,该数组在模型中包含表字段。
向模型添加$ fillable。
您可以点击此链接以获取与Mass Assignment
答案 1 :(得分:0)
您创建文件Comments.php
模型,可以更新文件Comments.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comments extends Model
{
protected $fillable = [
'body',
'user_id',
'user_email',
'user_name',
'status',
'post_id',
'created_at',
'updated_at'
];
}