【问题标题】:"General error: 1364 Field 'user_id' doesn't have a default value" Laravel“一般错误:1364 字段 'user_id' 没有默认值” Laravel
【发布时间】:2021-01-20 15:40:11
【问题描述】:

在我的资源控制器中,在 store 方法中,我这样做:

public function store(Request $request)
    {
      $post = $request->all();
      $post['user_id'] = Auth::user()->id;

      Post::create($post);

        return redirect()->route('index');
    }

为什么我会收到错误消息:General error: 1364 Field 'user_id' doesn't have a default value?

【问题讨论】:

  • 尝试 put static `$post['user_id'] = 4;` 并检查
  • 您的用户实际登录了吗?返回 Auth::user()->id 看看里面有什么
  • 是的,他已登录。问题是我没有将user_id 添加到protected $fillable。

标签: mysql laravel


【解决方案1】:

您应该在 Post 模型的 $fillable 属性中添加 'user_id' 以支持 mass assignment

class Postextends Model

{
protected $fillable=['user_id']; // not only user_id but also all the fill able columns
} 

【讨论】:

  • 真的!谢谢!出于某种原因,我认为我们只需要向$fillable 添加我们从input 获得的那些字段。
【解决方案2】:

你应该像这样在可填充中使用 user_id,

class Postextends Model
{
    protected $fillable=['user_id'];
} 

您也可以将 $guarded 属性设置为,

class Postextends Model
{
    protected $guarded=[];
}

那么你就不需要设置propertise filable了。

注意: 虽然 $fillable 用作应该可以批量分配的属性的“白名单”,但您也可以选择使用 $guarded。 $guarded 属性应包含您不希望被大量分配的属性数组。不在数组中的所有其他属性都可以批量分配。因此,$guarded 的功能类似于“黑名单”。当然,您应该使用 $fillable 或 $guarded — 不能同时使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-25
    • 2021-03-22
    • 2017-11-10
    • 1970-01-01
    • 2021-09-10
    • 2019-11-23
    • 2019-01-05
    • 2021-08-11
    相关资源
    最近更新 更多