Laravel updateOrCreate一般错误字段post_id不存在 [英] Laravel updateOrCreate general error field post_id doesn't exist

查看:1263
本文介绍了Laravel updateOrCreate一般错误字段post_id不存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在数据库中有一个视图表,我正在尝试更新其中的记录(或创建它,如果它还不存在)与此代码:

  $ 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆