簡體   English   中英

如何在 Laravel 中制作沒有主鍵的表格?

[英]How to make table without primary key in Laravel?

我需要一對一地連接數據庫中的兩個表。 第一個表中的“id”需要是第二個表中的“id”。

表格1:

public function up()
{
    Schema::disableForeignKeyConstraints();

    Schema::create('devices', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('device_type', 20)->nullable();
        $table->date('purchase_date')->nullable();
        $table->date('activation_date')->nullable();
        $table->date('deactivation_date')->nullable();
        $table->bigInteger('companyId')->unsigned();
        $table->timestamps();

        $table->foreign('companyId')->references('id')->on('companies');

    });
    Schema::enableForeignKeyConstraints();

}

表 2:

public function up()
{
    Schema::disableForeignKeyConstraints();

    Schema::create('device_news', function (Blueprint $table) {
        $table->integer('x', 10)->nullable();
        $table->integer('y', 10)->nullable();
        $table->time('time')->nullable();
        $table->bigIncrements('deviceId');

        $table->timestamps();

        $table->foreign('deviceId')->references('id')->on('devices');
    });

    Schema::enableForeignKeyConstraints();

}

我從來沒有遇到過這樣的情況。 這是正確的還是我必須改變一些東西?

你仍然應該有一個$table->bigIncrements('id'); 在第二個表上,因此該表獲得一個 PK - 但是您在一個非主鍵的無符號 biginteger 上創建關系。

Laravel 命名約定還規定關系列應該是device_id而不是deviceId (主表也是如此,它應該是company_id而不是companyId )。 當您開始在模型上定義關系時,這樣做將使您的生活變得更加輕松。

Schema::create('device_news', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->unsignedBigInteger('device_id');
    $table->integer('x', 10)->nullable();
    $table->integer('y', 10)->nullable();
    $table->time('time')->nullable();

    $table->timestamps();

    $table->foreign('device_id')->references('id')->on('devices');
});

要為沒有主鍵的舊表創建 Eloquent 模型,只需將以下內容添加到您的模型中:

/**
 * primaryKey 
 * 
 * @var integer
 * @access protected
 */
protected $primaryKey = null;

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM