I have a scenario with Articles
and Categories
where each article can have only one category through a CategoryGroup
.
This means the article
can have more than one category
but only one unique category from each category_group
. Or, to put it another way, the article can have only one category from each category_group
.
Do I model this scenario at the level of relationships? Or is this a matter of using custom validation?
This seems like a hasOneThrough
scenario but this doesn't exist. So what's the workaround?
I have tried a many-to-many relationship
between articles and categories but how do I constrain the article from having more than one of each category type while attaching categories to single articles?
Schema::create('articles', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('body');
$table->string('slug');
$table->timestamps();
});
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->text('description');
$table->string('slug');
$table->string('handle');
$table->integer('category_group_id')->index()->nullable();
$table->timestamps();
});
Schema::create('article_category', function (Blueprint $table) {
$table->integer('article_id')->unsigned();
$table->integer('category_id')->unsigned();
$table->primary(['article_id', 'category_id']);
$table->timestamps();
});