0
votes

I'm new to Laravel and ORMs in general, and I'm trying to port a site I've already written over to it. I have one table that defines genres, and relate a books table to it by relating them through the book having a genre_id.

Is this a one-to-many relationship? It feels weird to say that a book "belongs to" a genre and a genre "has many" books. I'd rather say that a book "has" a genre and a genre "belongs to many" books, but that doesn't seem to exist.

2

2 Answers

1
votes

If the genre_id is in the books table then the Book belongsTo a Genre. The Genre hasMany books.

If the a table has both a primary key and a foreign key (genre_id is a FK to another table) then that record belongsTo.

Your first guess was correct. It takes a bit to understand the relationship semantics, but once you understand them it's a breeze to reference.

This post from a while ago got me on track to understanding the different relationships: http://forums.laravel.io/viewtopic.php?pid=11819#p11819

1
votes

In SQL you're stuck with the "has-many" terminology. As in, a genre "has_many" books. One way to try to wrap your head around it is that say that many books will have the same, one genre. This is the origin of the one-to-many phrasing. If a book can have multiple genres (such as horror-comedy-romance) you might want to think about it as a many-to-many relationship.