@verism
If you are looking for optimization, maybe, I am not certain.
However, you could go with $table->smallInteger('gender_id')->unsigned()->nullable()->default(null); to keep this extra field minimal. (Or even tinyInteger, but this is not supported in all Databases, like PostgreSQL for example will convert it to boolean)
In any case, here it is for manyToMany:
User Model:
public function genders() {return $this->belongsToMany(Gender::class)->withTimestamps();}
On the Gender Model:
public function users() {return $this->belongsToMany(User::class)->withTimestamps();}
You also need a gender_user table with the following:
public function up()
{
Schema::create('gender_user', function (Blueprint $table) {
$table->integer('gender_id')->unsigned();
$table->integer('user_id')->unsigned();
$table->timestamps();
$table->foreign('gender_id')
->references('id')
->on('genders')
->onUpdate('cascade')
->onDelete('cascade');
$table->foreign('user_id')
->references('id')
->on('users')
->onUpdate('cascade')
->onDelete('cascade');
});
}
Notice gender_user is in Alphabetical Order. This is done so laravel can automate a few things for you, otherwise you will need to specify the table names and primary_keys for each table.
Then to attach a Gender to a User:
User::find($id)->sync($genderID);
Sync will remove any IDs that are not specified, and attach the specified ones. Like if you had more than 1-gender, then you should pass an array here. It will detach any Genders not present in the Array, and attach the ones that you are passing. If they are already there, it will do nothing.
More on this here:
Many to Many Relationships
and here:
Pivot tables and many-to-many relationships