【问题标题】:How to disable Laravel eloquent Auto Increment?如何禁用 Laravel 雄辩的自动增量?
【发布时间】:2018-01-03 05:17:55
【问题描述】:

我需要一种有效的方法来禁止 Laravel 自动识别我要插入数据的表的主键。

为什么?我不检查数据库和插入的数据之间是否有任何重复,所以如果有任何重复,我只是在 try-catch 块中处理它。

问题是如果有任何失败,Laravel 会像我插入一行一样计算它。所以 IDs 列不会按照 [1, 2, 3, etc] 的顺序排列,而是按照 [1, 4, 8, 20, etc] 的顺序排列。

我对这个问题进行了很多搜索,并尝试在声明类之后使用这一行:

public $autoincrement = false;

还有

public $incrementing = false;

但它们不工作。

我只想使用我的数据库的 AI。不是 Laravel 的。

【问题讨论】:

  • "不是 Laravels one" 你是什么意思?你也试过我的回答吗?也请分享你的模型
  • 我试了大约 3 次,但还是不行!我不知道为什么!

标签: php laravel eloquent


【解决方案1】:

试试public $incrementing = false;

【讨论】:

  • 我也用过,但是什么也没发生。
【解决方案2】:

您必须在表迁移文件中声明新的主键:

$table->primary('new_key_column');

当然,您必须像以前一样在模型中禁用自动增量。

【讨论】:

  • 问题是我的项目中没有使用迁移,我只是通过 phpmyadmin 与我的数据库交互。
【解决方案3】:

如果你想使用non-incrementing or a non-numeric primary key,你必须在你的模型上使用set the public $incrementing propertyfalse

例如:

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

    public $incrementing = false;
}

在迁移的情况下:

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

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

【讨论】:

  • 我确实多次使用这些行但没有任何结果。我也不使用迁移。
  • 请分享您的模型
  • 我刚刚找到了解决方案并发布了它。你可以检查一下。
【解决方案4】:

您的问题有 2 个解决方案。 如您所说,第一个是禁用增量列。为此,只需转到您的迁移,然后更改

$table->increment('id)`

$table->integer('id')

它将删除主键,设置主键,只需转到您的模型文件并添加以下内容:

protected $primaryKey = 'column_name';

我更喜欢第二种解决方案。无论何时插入、更新或删除记录,甚至有时读取记录,都使用 laravel 的 DB 事务。这是一个例子:

DB::beginTranscation();
try {
    $model = new Model;
    $model->column_name = $value;
    $model->save();
    DB::commit()
    return;
}
catch(exception $e) {
    DB::rollback();
    return;
}

这种方法比删除自动增量要好。但现在由您来选择。

【讨论】:

    【解决方案5】:

    您可以执行以下操作

    表:作者

    列:id、name、active

    class Author extends Model
    {
        /**
         * Configure the Model variables
         *
         */
        protected $table = 'author';
        protected $primaryKey = 'id';
        protected $fillable = ['name', 'active']; // eloquent Will use only these columns as you are mentioning them as fillable.
    
        public static function saveAuthor($data) {
             $author = Author::firstOrNew(['name' => $data['name']]);
    
                $author->name = $data['name'];
                $author->active = 1;
                $author->save();
        }
    }
    

    在 fillable 中,您可以定义要通过模型更改或更新的列。其余字段的行为将根据 mysql 定义。

    希望对你有帮助。

    【讨论】:

    • 嗯,谢谢,但没有尝试,这个解决方案对我的项目真的有害。它是一个庞大的系统,我无法在所有模型和流程中都这样做。谢谢。
    【解决方案6】:

    抱歉,各位,耽误了你们的时间, 问题是,如果我们尝试在 MYSQL 中保存任何记录,无论它出于任何原因返回成功还是失败(比如我的情况是重复),

    MYSQL 认为自动增量号已被预订,并且任何其他即将到来的记录都不会占用它,因为可能同时在 DB 上存在多个插入过程并等待知道自动增量号是否为预订与否都会影响 MYSQL 的速度。

    所以这不是 Laravel 的问题,而是 MYSQL 的问题。

    我希望它可以帮助其他人。

    谢谢大家...

    【讨论】:

      【解决方案7】:

      这是创建其名称 site_rules 的表的示例,这是我添加以下行以使 id 为主并自动递增的迁移文件
      //add this line to make id auto incremented from a specified value DB::statement("ALTER TABLE site_rules AUTO_INCREMENT = 1;"); 这是迁移文件代码:

      <?php
      
       use Illuminate\Support\Facades\Schema;
       use Illuminate\Database\Schema\Blueprint;
       use Illuminate\Database\Migrations\Migration;
      class SiteRules extends Migration
      {
      /**
       * Run the migrations.
       *
       * @return void
       */
      public function up()
      {
          Schema::create('site_rules', function (Blueprint $table){
              $table->increments('id');
              $table->string('name_ar');
              $table->string('name_en'); 
              $table->timestamps();
          });
          //add this line to make id auto increment from a specified value 
          DB::statement("ALTER TABLE site_rules AUTO_INCREMENT = 1;");
      }
      
      /**
       * Reverse the migrations.
       *
       * @return void
       */
      public function down()
      {
          Schema::dropIfExists('site_rules');
      }
      }
      

      试试看

      【讨论】:

        【解决方案8】:

        你可以使用

        public function up()
        {
            Schema::create('users', function (Blueprint $table) {
                $table->integer('matricule')->unsigned();;
                $table->primary(['matricule']);
                $table->string('nometprenom');
                $table->string('age');
                $table->string('adresse');
                $table->string('telephone');
                $table->string('login');
                $table->string('password');
                $table->string('type');
                $table->engine = 'InnoDB';
                
            });
        }
        

        【讨论】:

          【解决方案9】:

          在您的模型中:

          public $incrementing = false;
          

          在您的迁移中:

          //Remove the default $table->id();
          
          //second param is what auto-increments, default is false so can be skipped
          $table->unsignedBigInteger('id', false)->primary(); 
          

          快速评论您在此处看到的所有其他过时或错误的解决方案:

          • $primaryKey 不需要被覆盖,除非主列不同于“id”
          • 您不需要使用丑陋的数据库事务来消除自动递增!继续使用可爱的雄辩模型,并使用这个答案。

          【讨论】:

            猜你喜欢
            • 2016-07-09
            • 1970-01-01
            • 1970-01-01
            • 2023-03-16
            • 2014-11-08
            • 1970-01-01
            • 2023-03-11
            • 2022-07-25
            • 1970-01-01
            相关资源
            最近更新 更多