Skip to content

5. Relationships

DA edited this page Apr 3, 2019 · 19 revisions

In relational databases, tables are related to one another. There are several types of relationships that can be defined. This framework makes it easy to define and use relationships without having to write extensive code. There are 3 types of relationships defined in this framework: One-to-One, One-to-Many and Many-to-Many.

One-To-One Relationship

A One-to-One relationship is the simplest relationship between two entities. For example, we can have an authorization module where every User has one Account and reciprocally every Account has one User. This is a typical One-to-One relationship.

Definition

In order to create such a relationship, you first need to make sure that the database tables that you create for the two entities both have foreign keys that link to one another.

Learn more about Relational Databases here

Once your database tables are created, one of the models User, for example, will add a new method that invokes the hasOne() method to define that relationship.

class User extends Model {
    // properties go here
    //...

    //new method that defines a One-to-One relationship
    public function accounts()
    {
       return $this->hasOne('Account','accounts');
       // the first argument is the model name to link to
       // the second argument is the database table name of to link to

    }
}

Inverse Relationship

In the Account model, you will need to do the same using the hasOne method.

class Account extends Model {
    // properties go here
    //...

    //new method that defines the inverse of a One-to-One relationship
    public function users()
    {
       return $this->hasOne('User','users');
       // the first argument is the model name to link to
       // the second argument is the database table name of to link to

    }
}

Usage

Clone this wiki locally