完整性约束违规:1452无法添加或更新子行

时间:2016-12-11 06:24:27

标签: mysql laravel-5

我收到了这个错误:

SQLSTATE [23000]:完整性约束违规:1452无法添加或更新子行:外键约束失败(pumma2users,CONSTRAINT users_roles_id_foreign FOREIGN KEY({{ 1}})REFERENCES roles_idusers)ON DELETE CASCADE ON UPDATE CASCADE)(SQL:插入idusersusername,{{1 }},emailnamepasswordcoverroles_id)值(qweqwe,haikalhikmi @ gmail.com,qweqweqew,$ 2y $ 10 $ YX2OPPTGEDcquYkgk .ln6eEuwtFqrtmRbIpvgEZqJJHR9gk8mfdfm,壁纸-27058.jpg,1,1004-12-11 06:09:41,2016-12-11 06:09:41))

这是我的RegisterController



updated_at




当我尝试dd($ user)时:

它有效:



created_at




以防万一你想查看我的用户表



$user=$request->file('cover');
        $destination ='img/user';
        $filename=$user->getClientOriginalName();
        storage::put('img/user/'.$filename,file_get_contents($request->file('cover')->getRealPath()));
 
        $user = new User();
                
        $user->username = $request->username;
        $user->email = $request->email;
        $user->name = $request->name;
        $user->password = bcrypt($request->password);
        $user->cover = $filename;
        $user->roles_id = DB::table('roles')->select('id')->where('rolename','user')->first()->id;       
                 
        $user->save();




1 个答案:

答案 0 :(得分:1)

从上面的代码中,用户与角色属于所有关系。因此,用户外键的迁移应为

schema::table('users', function (Blueprint $table){            
        $table->foreign('roles_id')->references('id')->on('roles')->onDelete('cascade')->onUpdate('cascade');

});  

roles_id列应引用id表上的roles列,而不是users表。

更改外键应该可以帮助您摆脱约束违规。

更新(以下评论中对OP查询的更多解释)

在问题的RegisterController代码中

$user->roles_id = DB::table('roles')->select('id')->where('rolename','user')->first()->id;  

引发异常,因为DB::table('roles')->select('id') - 这部分将返回一个整数,从->where('rolename','user')->first()->id开始链接就像试图在普通整数上找到一个属性,这将导致异常。

因此查询可以定义为

$user->roles_id = DB::table('roles')->where('rolename', 'user')->first()->id;

/* 
    Or - to get just the id instead of the entire record 
 */ 

$user->roles_id = DB::table('roles')->where('rolename', 'user')->value('id'); 

/* 
    Or - if there is a Role model defined corresponding to the roles table 
 */

$user->roles_id = \Role::where('rolename', 'user')->first()->id;