作者:手机用户2702937405 | 来源:互联网 | 2023-02-05 14:47
我试图为user_id分配当前用户,但它给了我这个错误
SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a
default value (SQL: insert into `posts` (`updated_at`, `created_at`)
values (2017-04-27 10:29:59, 2017-04-27 10:29:59))
这是我的方法
//PostController
Post::create(request([
'body' => request('body'),
'title' => request('title'),
'user_id' => auth()->id()
]));
与这些填料
//Post Model
protected $fillable = ['title', 'body', 'user_id']
然而,这种方法可以胜任
//PostController
auth()->user()->publish(new Post(request(['title' ,'body'])));
//Post Model
public function publish(Post $post)
{
$this->posts()->save($post);
}
知道为什么会失败吗?
1> Shailesh Lad..:
打开database.php并找到config/database.php
将值true更改为false,然后重试
2> Mohammed Sab..:
所以,在再次检查代码之后,我发现了错误.我想知道没有人注意到这一点!在上面的代码我写道
Post::create(request([ // <= the error is Here!!!
'body' => request('body'),
'title' => request('title'),
'user_id' => auth()->id()
]));
实际上,不需要请求函数来扭曲create函数的主体.
// this is right
Post::create([
'body' => request('body'),
'title' => request('title'),
'user_id' => auth()->id()
]);
3> Mayur Buduka..:
这是我的操作方式:
这是我的PostsController
Post::create([
'title' => request('title'),
'body' => request('body'),
'user_id' => auth()->id()
]);
这是我的帖子模型。
protected $fillable = ['title', 'body','user_id'];
如果只是在测试实例上,请尝试刷新迁移
$ php artisan migrate:refresh
注意:迁移:刷新将删除所有以前的帖子,用户
如果您在控制器中没有语法错误,则将`user_id`添加到fillable将解决该问题,但是为什么要刷新迁移?