我有两个必须具有相同ID的表。这是我第一次在DB中遇到问题。
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();
});
第二张桌子应该像这样吗?
Schema::create('device_news', function (Blueprint $table) {
$table->bigIncrements('id');
$table->float('x', 10);
$table->float('y', 10);
$table->time('time')->nullable();
$table->unsignedBigInteger('deviceId');
$table->timestamps();
$table->foreign('deviceId')->references('id')->on('devices');
});
我对此并不陌生,对此有些困惑
我建议您使用laravel ORM relationship,您不需要具有相同的ID,但是您可以在device_news中将设备ID用作外键:
在设备模型中,您可以添加如下代码:
public function deviceNew()
{
return $this->hasOne('App\DeviceNew');
}
并且在设备新模型中,您可以添加如下代码:
public function device()
{
return $this->belongTo('App\Device', 'deviceId');
}
然后您可以像这样从设备模型中调用device_news表:
$new = Device::find(1)->deviceNew;