Laravel - 违反完整性约束:1062 重复条目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37954214/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:02:53  来源:igfitidea点击:

Laravel - Integrity constraint violation: 1062 Duplicate entry

mysqllaravellaravel-5.2

提问by Bullgod

i have a problem when i try to create a new user in my database, if I add the users in phpmyadmin i have no problems, but when i try create users in my laravel web, the users has created with this error: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '15.236.964-5' for key 'PRIMARY' I dont have idea which is the problem because in the database does not exist the same primary key. The table with problems is:

当我尝试在我的数据库中创建一个新用户时遇到问题,如果我在 phpmyadmin 中添加用户我没有问题,但是当我尝试在我的 laravel web 中创建用户时,用户创建了这个错误:SQLSTATE[23000 ]:违反完整性约束:1062 键“PRIMARY”的重复条目“15.236.964-5”我不知道这是问题所在,因为在数据库中不存在相同的主键。有问题的表是:

CREATE TABLE IF NOT EXISTS `users` (
`rut` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `password` char(60) COLLATE utf8_unicode_ci NOT NULL,
  `edad` int(11) NOT NULL,
  `pais` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `comuna` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `sector` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `tipo` enum('profesor','alumno','administrador_parrilla','administrador_sistema','externo') COLLATE utf8_unicode_ci NOT NULL,
  `remember_token` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

ALTER TABLE `users`
  ADD PRIMARY KEY (`rut`),
  ADD UNIQUE KEY `usuario_rut_unique` (`rut`),
  ADD UNIQUE KEY `usuario_email_unique` (`email`);

My controller:

我的控制器:

class UsuarioController extends Controller
{
 public function index(){
        $users = User::All();
        return view('usuario.index', compact('users'));
    }

    public function create(){
     return view('usuario.create');
    }
    public function store(Request $request) {
         User::create([
             'name' => $request['name'],
             'rut' => $request['rut'],
             'email' => $request['email'],
             'password' => bcrypt($request['password']),             
             'edad' => $request['edad'],
             'pais' => $request['pais'],
             'comuna' => $request['comuna'],
         ]);
        User::create($request->all());
        return redirect('/usuario')->with('message', 'store');
    }

    public function edit($rut){
        $user = User::find($rut);
        return view ('usuario.edit',['user'=>$user]);
    }

    public function update($id, Request $request){
        $user = User::find($id);
        $user -> fill($request->all());
        $user -> save();

        Session::flash('message', 'Usuario Editado Correctamente');
        return Redirect ('/usuario');
    }
}

My Model:

我的型号:

class User extends Authenticatable
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $table = "users";
    protected $fillable = [
        'rut', 'name', 'email', 'password', 'edad', 'pais', 'comuna', 'sector', 'tipo',
    ];
/**
    protected $primaryKey = 'rut';

    
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

I can't change the primary key adding auto_increment because i use the "Rut" as a primary key who is the code of identification to people in Chile.

我无法更改添加 auto_increment 的主键,因为我使用“Rut”作为主键,它是智利人的身份识别码。

采纳答案by Bullgod

The problem was a line of code in the controller. The solution was simply to comment this line:

问题是控制器中的一行代码。解决方案只是评论这一行:

User::create($request->all());

Thanks for the answers.

感谢您的回答。

回答by num8er

Do following steps:

执行以下步骤:

1) Remove ADD UNIQUE KEY usuario_rut_unique (rut).

1)删除ADD UNIQUE KEY usuario_rut_unique (rut)

Because You already defined that rutis primary key, so PKs are always unique (it's PKs behaviour)

因为您已经定义了rut主键,所以 PK 总是唯一的(这是 PK 的行为)

2) Define in Your model that rutis primary key, and disable auto incrementing because it's varchar (not int cannot be iterated naturally) :

2)在您的模型中定义rut主键,并禁用自动递增,因为它是 varchar (不是 int 不能自然迭代):

/**
 * primaryKey 
 * 
 * @var integer
 * @access protected
 */
protected $primaryKey = 'rut'; 
/*
You cannot comment it to make in disabled, it will look for `id` param by default.
You cannot set it to be = null because in Your code You use ::find() function 
that looks for primaryKey.
 */

/**
 * Indicates if the IDs are auto-incrementing.
 *
 * @var bool
 */
public $incrementing = false;

3) Remove this line:

3)删除这一行:

User::create($request->all());

because You're already inserting record to database in previous line.

因为您已经在上一行中将记录插入到数据库中。

回答by Sachith Muhandiram

I got it many times with my project. Here it looks you first made a mistake making a table without a Primary Key, then you made it without making unique.
I think you better to check your database tables using a Graphical User Interface, such as MySQL Workbench.

我的项目多次得到它。在这里看起来您首先在制作没有主键的表格时犯了一个错误,然后您在没有制作唯一键的情况下制作了它。
我认为您最好使用图形用户界面(例如 MySQL Workbench)检查数据库表。

Then make sure your view's input field has the same name attribute as your database column names. That was the main thing I got errors.

然后确保视图的输入字段与数据库列名称具有相同的名称属性。这是我遇到错误的主要原因。

{!! Form::text('rut',null,['class'=>'form-control']) !!}