Hello, on the app i'm building Users will have the option to subscribe. I'm a bit confused if I should have a 'subscription_id' field on 'create_users_table' or if it should be the other way, having a 'user_id' on the 'create_subscription_table'. I'm also a bit confused on the model relationship at the moment I have them like this.
'create_users_table'
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('username');
$table->string('name');
$table->text('avatar')->nullable();
$table->string('email')->unique();
$table->integer('phone')->unique();
$table->string('address');
$table->string('country');
$table->string('province');
$table->string('city');
$table->timestamp('email_verified_at')->nullable();
$table->string('password'); // hashed in setPasswordAttribute function on user model
$table->foreignId('role_id')->constrained()->cascadeOnDelete();
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
};
'create_subscription_table'
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('subscriptions', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained('users','id')->cascadeOnDelete();
$table->dateTime('start_date');
$table->dateTime('next_billing_date');
$table->boolean('subscribed');
$table->float('price');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('subscriptions');
}
};
User model relationship
public function subscription() {
return $this->belongsTo(Subscription::class, 'subscription_id');
}
Subscription model relationship
public function subscribers()
{
return $this->hasMany(User::class);
}
I'm a bit confused and I'm not sure on how should I structure this or what should be the best way.