51 lines
1.8 KiB
PHP
51 lines
1.8 KiB
PHP
|
|
<?php
|
||
|
|
|
||
|
|
use Illuminate\Database\Migrations\Migration;
|
||
|
|
use Illuminate\Database\Schema\Blueprint;
|
||
|
|
use Illuminate\Support\Facades\DB;
|
||
|
|
use Illuminate\Support\Facades\Schema;
|
||
|
|
|
||
|
|
return new class extends Migration
|
||
|
|
{
|
||
|
|
public function up(): void
|
||
|
|
{
|
||
|
|
Schema::create('trackers', function (Blueprint $table) {
|
||
|
|
$table->id();
|
||
|
|
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
|
||
|
|
$table->foreignId('asset_id')->nullable()->constrained()->nullOnDelete();
|
||
|
|
$table->string('label');
|
||
|
|
$table->string('unit');
|
||
|
|
$table->boolean('price_tracking_enabled')->default(false);
|
||
|
|
$table->timestamps();
|
||
|
|
});
|
||
|
|
|
||
|
|
// Migrate existing users: create one tracker per user from their current asset_id + price_tracking_enabled
|
||
|
|
DB::table('users')->orderBy('id')->each(function (object $user) {
|
||
|
|
DB::table('trackers')->insert([
|
||
|
|
'user_id' => $user->id,
|
||
|
|
'asset_id' => $user->asset_id,
|
||
|
|
'label' => 'Portfolio',
|
||
|
|
'unit' => 'shares',
|
||
|
|
'price_tracking_enabled' => $user->price_tracking_enabled ?? false,
|
||
|
|
'created_at' => now(),
|
||
|
|
'updated_at' => now(),
|
||
|
|
]);
|
||
|
|
});
|
||
|
|
}
|
||
|
|
|
||
|
|
public function down(): void
|
||
|
|
{
|
||
|
|
// Restore asset_id and price_tracking_enabled back onto users before dropping trackers
|
||
|
|
DB::table('trackers')->orderBy('id')->each(function (object $tracker) {
|
||
|
|
DB::table('users')
|
||
|
|
->where('id', $tracker->user_id)
|
||
|
|
->update([
|
||
|
|
'asset_id' => $tracker->asset_id,
|
||
|
|
'price_tracking_enabled' => $tracker->price_tracking_enabled,
|
||
|
|
]);
|
||
|
|
});
|
||
|
|
|
||
|
|
Schema::dropIfExists('trackers');
|
||
|
|
}
|
||
|
|
};
|