When you work with data models you will come along the question of relationships between your models, or data tables. Most frameworks support this out of the box, and come with advanced features for handling such issues. You can take a look at the documentation for relationships for some of the major PHP projects on the matter:
What do the different types of relationships mean?
There are four basic types of relationships between models, and they are all distinguished by the way they store the foreign keys, i.e. how the relation is stored in the database.
Example 1: Author has many Books
- You have an Author table with a field Author.id.
- You have a Book table, with a field Book.authorId
In this example, each Author can have multiple books, while each Book belongs to one Author. The “has many” relationship is similar to “has one”, where Book would also store the Author id, however, the model logic implies that each Author can only have one book.
Example 2: Author has and belongs to many Tags
- You have an Author table with a field Author.id
- You have a Tag table with a field Tag.id
- Your have a relationship table AuthorTag with a field AuthorTag.authorId and AuthorTag.tagId
In this example each Author can have multiple tags, while each tag can be attached to multiple authors. This method required the intermediary relationship table.
Beware of identifying or non-identifying relationships
Some data models use the concepts of uniquely or non-uniquely identifying relationships. Please read more about this here, since it can affect the way your data model interacts with data, and produce unexpected results.
No comments yet (leave a comment)