繁体   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