Servage Magazine

Information about YOUR hosting company – where we give you a clear picture of what we think and do!

Relationship types between models

Saturday, March 16th, 2013 by Servage

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.

Relationship types between models, 3.7 out of 5 based on 3 ratings
Categories: Guides & Tutorials, Tips & Tricks

Keywords: ,

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

No comments yet (leave a comment)

You are welcome to initiate a conversation about this blog entry.

Leave a comment

You must be logged in to post a comment.