I have three tables categories
, film_categories
and films
and three models respectively Category
, FilmCategory
and Film
.
I have seen many tutorials where they don’t create a pivot table model
like i have created FilmCategory
Model . They just create a pivot table film_categories
without a model.
My question is what is the best practise – ?
Should i create a FilmCategory
model and set a hasMany
relationship
class Film extends Model
{
use HasFactory;
protected $primaryKey = 'film_id';
/**
* Film film Relationship
*
* @return IlluminateDatabaseEloquentRelationsHasMany
*/
public function categories()
{
return $this->hasMany(FilmCategory::class, 'film_id', 'film_id');
}
}
OR
Should i just create a pivot table film_categories
without a model FilmCategory
and set belongsToMany
relationship
class Film extends Model
{
use HasFactory;
protected $primaryKey = 'film_id';
/**
* Film film Relationship
*
* @return IlluminateDatabaseEloquentRelationsHasMany
*/
public function categoriesWithPivot()
{
return $this->belongsToMany(Category::class, 'film_categories', 'film_id', 'category_id');
}
}
2
Answers
Since the film_categories table does not represent an entity in your system, I think you should define a belongsToMany relationship and should not create a separate model for the pivot table. If You still wanna have a model for your pivot table so create a model that extends IlluminateDatabaseEloquentRelationsPivot class. Check documentation here: model for pivot table
Technically speaking, both option are fine. You can implement the two of them, and depends on what you want to implement/achieve in the logic part of the code, use one between the two that suits best. Here are things to consider:
First, depends on what is
film_categories
table used for. If the table is simply exists to relatefilms
andcategories
tables using many-to-many relationship, then there’s no need to create theFilmCategory
model, and you can just usebelongsToMany()
. Otherwise, if thefilm_categories
will relates to another table, then you should createFilmCategory
model and define the relation usinghasMany()
. You’re also likely need to add a primary-key field tofilm_categories
if this is the case.The second consideration to take is what kind of data structure you want to have. Using the codes that you provide, you can get
Film
s using these 2 queries and it’ll gives you the correct values but with different structures:And that’s it. The first point is mostly more important to consider than the second. But the choice is completely yours. I hope this helps.