我试图为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))
Run Code Online (Sandbox Code Playgroud)
这是我的方法
//PostController
Post::create(request([
'body' => request('body'),
'title' => request('title'),
'user_id' => auth()->id()
]));
Run Code Online (Sandbox Code Playgroud)
与这些填料
//Post Model
protected $fillable = ['title', 'body', 'user_id']
Run Code Online (Sandbox Code Playgroud)
然而,这种方法可以胜任
//PostController
auth()->user()->publish(new Post(request(['title' ,'body'])));
//Post Model
public function publish(Post $post)
{
$this->posts()->save($post);
}
Run Code Online (Sandbox Code Playgroud)
Lam*_*row 18
我今天在用户注册方面遇到了类似的问题,我得到了一个
SQLSTATE[HY000]: General error: 1364 Field 'password' doesn't have a default value (SQL: insert into users
Run Code Online (Sandbox Code Playgroud)
我通过添加password到受保护的 $fillable 数组来修复它并且它起作用了
protected $fillable = [
'name',
'email',
'password',
];
Run Code Online (Sandbox Code Playgroud)
我希望这有帮助。
Moh*_*bah 16
所以,在再次检查代码之后,我发现了错误.我想知道没有人注意到这一点!在上面的代码我写道
Post::create(request([ // <= the error is Here!!!
'body' => request('body'),
'title' => request('title'),
'user_id' => auth()->id()
]));
Run Code Online (Sandbox Code Playgroud)
实际上,不需要请求函数来扭曲create函数的主体.
// this is right
Post::create([
'body' => request('body'),
'title' => request('title'),
'user_id' => auth()->id()
]);
Run Code Online (Sandbox Code Playgroud)
这是我的操作方式:
这是我的PostsController
Post::create([
'title' => request('title'),
'body' => request('body'),
'user_id' => auth()->id()
]);
Run Code Online (Sandbox Code Playgroud)
这是我的帖子模型。
protected $fillable = ['title', 'body','user_id'];
Run Code Online (Sandbox Code Playgroud)
如果只是在测试实例上,请尝试刷新迁移
$ php artisan migrate:refresh
Run Code Online (Sandbox Code Playgroud)
注意:迁移:刷新将删除所有以前的帖子,用户
| 归档时间: |
|
| 查看次数: |
93129 次 |
| 最近记录: |