我在数据库中有一个 View 表,我正在尝试使用以下代码更新其中的一条记录(如果它尚不存在,则创建它):
$ar = ['number_of_views' => $number_of_views['number_of_views']+1, 'post_id' => $post->id];
App\View::updateOrCreate(['id' => $number_of_views['id']], $ar);
不幸的是,这会返回一个错误:
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))
它似乎无法识别 'post_id' => $post->id
因此返回一个错误,就好像它根本没有设置一样。
只有在要创建记录时才会出现此错误,如果记录已经存在则不会出现。
最佳答案
您需要将 post_id
字段添加到模型的 fillable 属性中以进行批量分配,如下所示:
protected $fillable = ['post_id', 'number_of_views'];
关于php - Laravel updateOrCreate 一般报错字段post_id不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42140131/