user783388
user783388

Reputation:

several tables with many-to-one relationship

I'm using octobercms which uses eloquent models.

I have several tables (Books, Movies, Comics...) and I need to link them to an agegroup table. Every book (movie, comic) gets exactly one agegroup.

My first intention was this:

table agegroup:
  id
  ...

table book:
  id
  agegroup_id
  ...

table movie:
  id
  agegroup_id
  ...

But I dont get how to put that into an Eloquent model.

Bonus question: there are other similar links (every book, movie etc. has exactly one section) where I need basically the same fields as in the agegroup table: should I reuse that (how?) or create another similar table?

Upvotes: 1

Views: 54

Answers (1)

Bogdan
Bogdan

Reputation: 44526

Relationships don't have a single direction, they're two-ways, so one-to-many is the same as many-to-one, only the perspective changes. Meaning that from one perspective a model has many others, and from the other a model belongs to another model. Even the naming used in defining the relationships is very intuitive: hasMany and belongsTo. So here's how you would configure the relationship between a Book model and a AgeGroup model.


A book belongs to only one age group:

class Book extends Model
{
    public $belongsTo = [
        'ageGroup' => 'Acme\Blog\Models\AgeGroup'
    ];
}

Then you can get the age group of a book like this:

Book::find(1)->ageGroup->name; // I'm assuming age groups have names

The revers of that relationship is that an age group can have many books associated to it:

class AgeGroup extends Model
{
    public $hasMany = [
        'books' => 'Acme\Blog\Models\Book'
    ];
}

Then you can get all books that belong to an age group like so:

foreach (AgeGroup::find(1)->books as $book) {
   // access book details like: $book->title;
}

The same logic applies to movies and whatever other entities that can have one age group.

Upvotes: 0

Related Questions