php - Laravel 4,eloquent mysql 表设计问题

标签 php mysql laravel-4 relational-database eloquent

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

 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`  
  ))    

最佳答案

增量会自动尝试将该字段设置为主键。因此,您不能使用它来自动增加您的头寸。 如果您的 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();

关于php - Laravel 4,eloquent mysql 表设计问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24140151/

相关文章:

mysql - 到期日期为 7 天前,并且没有其他事件

php - 菜单栏通知徽章更新问题

php - 数据库支持的输入字段的代理过滤器值

php - preg_match 解析html标签并插入变量

mysql - 从平面数据集中的父子表检索数据

laravel-4 - Laravel 4 - 与 Eloquent 的简单连接?

php - 如何将第三方类库与 Laravel 集成以使其自动加载?

javascript - PHP 将 Canvas 保存为图像时出现 500 Internal Server Error

php - MySQL日期格式排序错误

php - 在wordpress中使用php和ajax将数据插入mysql数据库