Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

php - How to disable Laravel eloquent Auto Increment?

I need an effective way to disable Laravel from auto incriminating the primary key of the table which I am going to insert data in.

Why? I don't check if there is any duplication between the DB and the inserted data so if there was any duplication I just handles it in a try-catch block.

The problem is if there was any failure Laravel counts it like I have inserted a row. So IDs column is not going to be in this order [1, 2, 3, etc], but in this [1, 4, 8, 20, etc].

I searched a lot about this issue and I have tried to use this line after the declaration of the class:

public $autoincrement = false;

Also

public $incrementing = false;

But they are not working.

I just want to use the AI of my DB. Not Laravel's one.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

if you wish to use a non-incrementing or a non-numeric primary key you must set the public $incrementing property on your model to false.

eg :

class UserVerification extends Model
{
    protected $primaryKey = 'your_key_name'; // or null

    public $incrementing = false;
}

in case of migration :

$table->integer('id')->unsigned(); // to remove primary key 
$table->primary('id'); //to add primary key

refer : https://laravel.com/docs/5.3/eloquent#eloquent-model-conventions


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...