【问题标题】:Laravel 4,eloquent mysql table design issueLaravel 4,雄辩的mysql表设计问题
【发布时间】:2014-07-31 03:59:38
【问题描述】:

我希望能够设计一个具有以下内容的数据库;

 customer
 --------------
 id(int) | name

 Company
 -------------------------
 id(int) | name | location 

 queue
 --------------------------------------------------------------------------------
 id (datetime-primary but not auto-increment) | company_id | customer_id | position (not primary but auto-increment)

 customer_queue
 -----------------------
 customer_id | queue_id

public function up()
{
    Schema::create('queues', function(Blueprint $table)
   {
    $table->dateTime('id')->primary();  //dateTime for id since one is genereated every other working day
    $table->integer('company_id')->unsigned();
        $table->foreign('company_id')->references('id')->on('companies');
        $table->integer('customer_id')->unsigned();
        $table->foreign('customer_id')->references('id')->on('customers');
        $table->increments('position');
        $table->time('start_time');
        $table->time('end_start');
        $table->integer('type');
        $table->time('joined_at');
        $table->time('left_at');
        $table->integer('customer_queue_status');
        $table->timestamps();
    //$table->primary(array('id', 'position'));
    });
    //find a way to make position auto-increment without being primary and rather set id to primary without auto-incrementing
}

我正在使用具有 eloquent 的 laravel 4,它不允许我在队列表中仅指定主要的 id,然后使位置自动递增而不是主要的。

我得到的错误如下

>This is the error i get
>[Illuminate\Database\QueryException]                                         
  SQLSTATE[42000]: Syntax error or access violation: 1068 Multiple primary ke  
  y defined (SQL: alter table `queues` add primary key queues_id_primary(`id`  
  ))    

【问题讨论】:

  • 请发布您当前的迁移/设置和队列模型的代码
  • @MatthiasS 感谢您的回复。我已经添加了队列迁移,但队列模型中还没有代码。因为数据库仍然无法正常工作。
  • 你应该重新考虑你的模型。自动增量仅限于主键。您需要使用 PHP 自己增加位置。
  • @dave 感谢您的建议,但是,我需要将 id 字段设置为 datetime 而不是 int 或自动递增它可以是唯一的,因为它只会更改或每隔一天创建一个新字段.
  • 我在其他地方读到了 protected $primaryKey = 'id';在模型中将起作用。我还可以使 id 键唯一,这将导致它被索引。这两者的结合能解决我的问题吗?

标签: php mysql laravel-4 relational-database eloquent


【解决方案1】:

增量会自动尝试将字段设置为主键。因此,您不能使用它来自动增加您的位置。 如果您的 id 字段设置为主要字段,则根据定义它是唯一的。

我认为没有办法自己实现自动增量。 我会以某种方式在您的队列模型中这样做:

 class Queue extends Eloquent {
    //....
    public static function boot() {
    parent::boot();

      static::creating(function($queue) {
        $position = DB::table('queues')->max('position');
        if(is_null($position)) $position = 0;
        $position++;
        $queue->position = $position;
        return true;

      });
    }
   //....
 }

这样每次保存Queue 模型时,它都应该寻找最高值并将其加一。如果您还没有条目,它将以 1 开头。 在您的架构中,设置$table->integer('position')->unique();

【讨论】:

    猜你喜欢
    • 2020-09-25
    • 1970-01-01
    • 2019-03-17
    • 2014-10-18
    • 2013-09-09
    • 2015-06-01
    • 1970-01-01
    相关资源
    最近更新 更多