goran_bl
goran_bl

Reputation: 69

Two tables with same ID in Laravel project

I have two tables that must have the same id. This is the first that I have alredy in 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();

    });

Should the second table look like this?

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

I'm new to this, I'm a little confused about it

Upvotes: 0

Views: 1268

Answers (1)

Adrian Edy Pratama
Adrian Edy Pratama

Reputation: 4031

I recommend you to use laravel ORM relationship, you don't need to have the same Id but you can use device id as a foreign key in device_news:

In the device model you can add code like this :

public function deviceNew()
{
    return $this->hasOne('App\DeviceNew');
} 

And in the device new model you can add code like this :

public function device()
{
    return $this->belongTo('App\Device', 'deviceId');
} 

Then you can call the device_news table from the device model like this :

$new = Device::find(1)->deviceNew;

EDIT : Try this too to meet your mentor expectation

In your DeviceNew model add this property :

public $incrementing = false;

Then every time you store the device make sure you make the device new too, like this :

$device = new Device();
$device->device_type = "type";
// Add other field too
$device->save();

$deviceNew = new DeviceNew();
$deviceNew->id = $device->id;
// Add other field too
$deviceNew->save();

Upvotes: 2

Related Questions