简体   繁体   中英

How to make table without primary key in Laravel?

I need to connect two tables in DB with relation one to one. Where 'id' from first table need to be the 'id' in the second table.

Table 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();

}

Table 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();

}

I never had situation like this. Is it correct or I have to change something?

You should still have a $table->bigIncrements('id'); on the second table, so the table gets a PK - but you create the relation on an unsigned biginteger, which is not a primary key.

Laravel naming conventions also dictates that a relational column should be device_id and not deviceId (same goes for your primary table, it should be company_id and not companyId ). Doing this will make your life much easier when you start defining your relations on your models.

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');
});

To create an Eloquent model for a legacy table that has no primary key, simply add the following to your model:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM