Laravel updateOrCreate一般错误字段post_id不存在 [英] Laravel updateOrCreate general error field post_id doesn't exist
问题描述
$ ar = ['number_of_views'=> $ number_of_views ['number_of_views'] + 1,'post_id'=> $后> ID];
App \View :: updateOrCreate(['id'=> $ number_of_views ['id']],$ ar);
不幸的是,这会返回一个错误:
SQLSTATE [HY000]:常规错误:1364字段'post_id'没有
默认值(SQL:插入视图
(number_of_views
,
updated_at
,created_at
)值(1,2017-02-09 14:41:19,2017-02-09
14:41:19))
似乎没有识别'post_id'=> $ post-> id
因此返回一个错误,就像没有设置一样。
只有当记录是要创建,而不是已经存在。
您需要添加 post_id
字段到模型上的可填充属性,如下所示:
protected $ fillable = ['post_id' ,'number_of_views'];
I have a views table in the database and i'm trying to update a record in it ( or create it if it doesn't exist yet) with this code:
$ar = ['number_of_views' => $number_of_views['number_of_views']+1, 'post_id' => $post->id];
App\View::updateOrCreate(['id' => $number_of_views['id']], $ar);
Unfortunately this returns an error:
SQLSTATE[HY000]: General error: 1364 Field 'post_id' doesn't have a default value (SQL: insert into
views
(number_of_views
,updated_at
,created_at
) values (1, 2017-02-09 14:41:19, 2017-02-09 14:41:19))
It seems that it isn't recognizing the 'post_id' => $post->id
hence returning an error as if it wasn't set at all.
This error only appears if the record is to be created and not if it already exists.
You need to add the post_id
field to the fillable attribute on the model for mass assignment like this:
protected $fillable = ['post_id', 'number_of_views'];
这篇关于Laravel updateOrCreate一般错误字段post_id不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!