I have 2 related tables. User and UserCategory table. And two are associated with category id.
User Table Scheme
public function up()
{
Schema::create('User', function (Blueprint $table) {
$table->id();
$table->string('name')->unique()->comment('User Name');
$table->foreignId('user_category_id')->constrained('UserCategory');
$table->string('user_category_name');
$table->foreign('user_category_name')->references('name')->on('UserCategory');
});
}
UserCategory Table Scheme
public function user_category()
{
return $this->belongsTo(UserCategory::class, 'user_category_id');
}
User Model
public function user_category()
{
return $this->belongsTo(UserCategory::class, 'user_category_id');
}
When I Create or Update Model, my ideal is just using category_id, then update with category_name field like this.
My Ideal
\App\Models\User::create([
'name' => 'Admin User',
'user_category_id' => 1, // ← not need to specify category_name.
]);
Or do I still have to update Like this?
In the current
\App\Models\User::create([
'name' => 'Admin User',
'user_category_id' => 1,
'user_category_name' => \App\Model\UserCategory::find(1)->name,// ← I don't want to do this.
]);
Is there a smarter way?
Thank you.