[英]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.
第一个表中的“id”需要是第二个表中的“id”。
Table 1:表格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:表 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');
你仍然应该有一个
$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.在第二个表上,因此该表获得一个 PK - 但是您在一个非主键的无符号 biginteger 上创建关系。
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
). Laravel 命名约定还规定关系列应该是
device_id
而不是deviceId
(主表也是如此,它应该是company_id
而不是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:要为没有主键的旧表创建 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.