簡體   English   中英

SQLSTATE [23000]:完整性約束違規:1048 列 'user_id' 不能是 laravel 中的 null

[英]SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id' cannot be null in laravel

我使用 vue 在 laravel 中創建了一個待辦事項應用程序。 我有兩個表:users 和 todos; 每個用戶都有很多這樣的待辦事項: User.php model:

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

待辦事項.php model:

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 的新手,感謝任何幫助!

你在關系中傳遞了錯誤的參數。

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


return $this->hasMany(Todos::class, 'foreign_key', 'local_key');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM