我使用 vue 在 laravel 中创建了一个待办事项应用程序。我有两个表:users 和 todos;每个用户都有很多这样的待办事项:User.php 模型:class User extends Authenticatable { protected $fillable = [ 'name', 'email', 'password', ]; public function todos() { return $this->hasMany( Todos::class, 'user_id', 'user_id' ); }}All.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 的新手,感谢您的帮助!
1 回答
HUWWW
TA贡献1874条经验 获得超12个赞
您在关系中传递了错误的参数。
public function todos()
{
return $this->hasMany(
Todos::class,'user_id','id'
);
}
return $this->hasMany(Todos::class, 'foreign_key', 'local_key');
- 1 回答
- 0 关注
- 105 浏览
添加回答
举报
0/150
提交
取消