【问题标题】:SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id' cannot be null in laravelSQLSTATE [23000]:违反完整性约束:1048 列 'user_id' 在 laravel 中不能为空
【发布时间】:2020-10-26 14:33:02
【问题描述】:

我在 laravel 中使用 vue 创建了一个 todo 应用程序。我有两个表:用户和待办事项;每个用户都有很多这样的待办事项: User.php 模型:

class User extends Authenticatable {
    protected $fillable = [
        'name', 'email', 'password',
    ];
    public function todos()
    {
        return $this->hasMany(
            Todos::class,
            'user_id',
            'user_id'
        );
    }
}

Todos.php 模型:

class Todos extends Model
{
    //
    protected $fillable = ['title', 'completed', 'user_id'];

    public function user()
    {
        return $this->belongsTo('App\User');
    }

然后我定义了这条路线:

Route::post('/v1/todo', 'todosController@addTodo');

这是我来自 todosController 的 addTodo:

 public function addTodo(Request $request)
    {
        $uid = Auth::user()->id;
        //dd($uid);

        $todoCreated = new Todos([
            'title' => $request->input('title'),
            'completed' => 0
        ]);
        $user = User::find($uid);
        //dd($user);

        //dd($todoCreated);
        dd($user->todos()->create([
            'title' => $request->input('title'),
            'completed' => 0,
        ]));
}

当我发送表单数据时,它向我显示此错误:Illuminate\Database\QueryException SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id' cannot be null (SQL: insert into todos (title, completed, user_id, updated_at, created_at) values (darya, 0, ?, 2020-07-06 12:17:45, 2020-07-06 12:17:45))。 我是 laravel 的新手,感谢任何帮助!

【问题讨论】:

    标签: php mysql laravel vue.js


    【解决方案1】:

    你在关系中传递了错误的参数。

    public function todos()
    {
        return $this->hasMany(
            Todos::class,'user_id','id'
        );
    }
    
    
    return $this->hasMany(Todos::class, 'foreign_key', 'local_key');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-01
      • 2017-07-31
      • 2020-08-07
      • 2019-11-20
      • 2021-08-16
      • 2019-10-06
      • 2020-10-25
      • 2017-02-28
      相关资源
      最近更新 更多