Eloquent: Relationships
Database tables are often related to one another.
Supports a variety of common relationships:
One to one relationship
The inverse of a one to one relationship
One to many relationship
The inverse of a one to many relationship
Many to many relationship
One To One
A one-to-one relationship is a very basic type of database relationship.
For example, a User
model might be associated with one Phone
model.
To define this relationship, we will place a phone
method on the Users
model.
The phone
method should call the hasOne
method and return its result.
The first argument passed to the hasOne
method is the name of the related model class. Once the relationship is defined, we may retrieve the related record using Eloquent's dynamic properties. Dynamic properties allow you to access relationship methods as if they were properties defined on the model:
Parameters:
The inverse of a one to one relationship
So, we can access the Phone
model from our User
model. Next, let's define a relationship on the Phone
model that will let us access the user that owns the phone. We can define the inverse of a hasOne
relationship using the belongOne
method:
Parameters:
One to many relationship
A one-to-many relationship is used to define relationships where a single model is the parent to one or more child models. For example, a blog post may have an infinite number of comments. Like all other Eloquent relationships, one-to-many relationships are defined by defining a method on your Eloquent model:
Parameters:
The inverse of a one to many relationship
use belong() method for the inverse of a one to many relationship.
Parameters:
Many To Many Relationship
Many to many relations are slightly more complicated than hasOne
and has
relationships.
use have() method.
Table Structure
Model Structure
Parameters:
Title of relationships
You can specify the title of the relationship using the method title().
You can specify the name of the child relationship using the method haveTitle().
Multiple relationships
You can use more than one relation.
Last updated