Laravel updateOrCreate 一般错误字段 post_id 不存在

Dom*_*WTF 5 php mysql sql laravel eloquent

我在数据库中有一个视图表,我正在尝试使用以下代码更新其中的记录(或者如果尚不存在则创建它):

$ar = ['number_of_views' => $number_of_views['number_of_views']+1, 'post_id' => $post->id];
App\View::updateOrCreate(['id' => $number_of_views['id']], $ar);
Run Code Online (Sandbox Code Playgroud)

不幸的是这会返回一个错误:

SQLSTATE[HY000]: 一般错误: 1364 字段 'post_id' 没有默认值 (SQL: 插入views( number_of_views, updated_at, created_at) 值 (1, 2017-02-09 14:41:19, 2017-02-09 14 :41:19))

似乎它无法识别,'post_id' => $post->id因此返回错误,就好像根本没有设置一样。

仅当要创建记录时才会出现此错误,如果记录已存在则不会出现此错误。

小智 8

您需要将该post_id字段添加到模型上的可填充属性中以进行批量分配,如下所示:

protected $fillable = ['post_id', 'number_of_views'];
Run Code Online (Sandbox Code Playgroud)