- Relationships
- Eloquent: Relationships
- Introduction
- Defining Relationships
- Many To Many Relationships
- Polymorphic Relationships
Relationships
Eloquent: Relationships
- Introduction
- Defining Relationships
- One To One
- One To Many
- One To Many (Inverse) / Belongs To
- Has One Of Many
- Has One Through
- Has Many Through
- Many To Many Relationships
- Retrieving Intermediate Table Columns
- Filtering Queries Via Intermediate Table Columns
- Ordering Queries Via Intermediate Table Columns
- Defining Custom Intermediate Table Models
- Polymorphic Relationships
- One To One
- One To Many
- One Of Many
- Many To Many
- Custom Polymorphic Types
- Dynamic Relationships
- Querying Relations
- Relationship Methods Vs. Dynamic Properties
- Querying Relationship Existence
- Querying Relationship Absence
- Querying Morph To Relationships
- Aggregating Related Models
- Counting Related Models
- Other Aggregate Functions
- Counting Related Models On Morph To Relationships
- Eager Loading
- Constraining Eager Loads
- Lazy Eager Loading
- Preventing Lazy Loading
- Inserting & Updating Related Models
- The save Method
- The create Method
- Belongs To Relationships
- Many To Many Relationships
- Touching Parent Timestamps
Introduction
Database tables are often related to one another. For example, a blog post may have many comments or an order could be related to the user who placed it. Eloquent makes managing and working with these relationships easy, and supports a variety of common relationships:
- One To One
- One To Many
- Many To Many
- Has One Through
- Has Many Through
- One To One (Polymorphic)
- One To Many (Polymorphic)
- Many To Many (Polymorphic)
Defining Relationships
Eloquent relationships are defined as methods on your Eloquent model classes. Since relationships also serve as powerful query builders, defining relationships as methods provides powerful method chaining and querying capabilities. For example, we may chain additional query constraints on this posts relationship:
$user->posts()->where('active', 1)->get();
But, before diving too deep into using relationships, let’s learn how to define each type of relationship supported by Eloquent.
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 User model. The phone method should call the hasOne method and return its result. The hasOne method is available to your model via the model’s Illuminate\Database\Eloquent\Model base class:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model;use Illuminate\Database\Eloquent\Relations\HasOne; class User extends Model{ /** * Get the phone associated with the user. */ public function phone(): HasOne { return $this->hasOne(Phone::class); }}
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:
$phone = User::find(1)->phone;
Eloquent determines the foreign key of the relationship based on the parent model name. In this case, the Phone model is automatically assumed to have a user_id foreign key. If you wish to override this convention, you may pass a second argument to the hasOne method:
return $this->hasOne(Phone::class, 'foreign_key');
Additionally, Eloquent assumes that the foreign key should have a value matching the primary key column of the parent. In other words, Eloquent will look for the value of the user’s id column in the user_id column of the Phone record. If you would like the relationship to use a primary key value other than id or your model’s $primaryKey property, you may pass a third argument to the hasOne method:
return $this->hasOne(Phone::class, 'foreign_key', 'local_key');
Defining The Inverse Of The 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 belongsTo method:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model;use Illuminate\Database\Eloquent\Relations\BelongsTo; class Phone extends Model{ /** * Get the user that owns the phone. */ public function user(): BelongsTo { return $this->belongsTo(User::class); }}
When invoking the user method, Eloquent will attempt to find a User model that has an id which matches the user_id column on the Phone model.
Eloquent determines the foreign key name by examining the name of the relationship method and suffixing the method name with _id. So, in this case, Eloquent assumes that the Phone model has a user_id column. However, if the foreign key on the Phone model is not user_id, you may pass a custom key name as the second argument to the belongsTo method:
/** * Get the user that owns the phone. */public function user(): BelongsTo{ return $this->belongsTo(User::class, 'foreign_key');}
If the parent model does not use id as its primary key, or you wish to find the associated model using a different column, you may pass a third argument to the belongsTo method specifying the parent table’s custom key:
/** * Get the user that owns the phone. */public function user(): BelongsTo{ return $this->belongsTo(User::class, 'foreign_key', 'owner_key');}
One To Many
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:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model;use Illuminate\Database\Eloquent\Relations\HasMany; class Post extends Model{ /** * Get the comments for the blog post. */ public function comments(): HasMany { return $this->hasMany(Comment::class); }}
Remember, Eloquent will automatically determine the proper foreign key column for the Comment model. By convention, Eloquent will take the “snake case” name of the parent model and suffix it with _id. So, in this example, Eloquent will assume the foreign key column on the Comment model is post_id.
Once the relationship method has been defined, we can access the collection of related comments by accessing the comments property. Remember, since Eloquent provides “dynamic relationship properties”, we can access relationship methods as if they were defined as properties on the model:
use App\Models\Post; $comments = Post::find(1)->comments; foreach ($comments as $comment) { // ...}
Since all relationships also serve as query builders, you may add further constraints to the relationship query by calling the comments method and continuing to chain conditions onto the query:
$comment = Post::find(1)->comments() ->where('title', 'foo') ->first();
Like the hasOne method, you may also override the foreign and local keys by passing additional arguments to the hasMany method:
return $this->hasMany(Comment::class, 'foreign_key'); return $this->hasMany(Comment::class, 'foreign_key', 'local_key');
One To Many (Inverse) / Belongs To
Now that we can access all of a post’s comments, let’s define a relationship to allow a comment to access its parent post. To define the inverse of a hasMany relationship, define a relationship method on the child model which calls the belongsTo method:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model;use Illuminate\Database\Eloquent\Relations\BelongsTo; class Comment extends Model{ /** * Get the post that owns the comment. */ public function post(): BelongsTo { return $this->belongsTo(Post::class); }}
Once the relationship has been defined, we can retrieve a comment’s parent post by accessing the post “dynamic relationship property”:
use App\Models\Comment; $comment = Comment::find(1); return $comment->post->title;
In the example above, Eloquent will attempt to find a Post model that has an id which matches the post_id column on the Comment model.
Eloquent determines the default foreign key name by examining the name of the relationship method and suffixing the method name with a _ followed by the name of the parent model’s primary key column. So, in this example, Eloquent will assume the Post model’s foreign key on the comments table is post_id.
However, if the foreign key for your relationship does not follow these conventions, you may pass a custom foreign key name as the second argument to the belongsTo method:
/** * Get the post that owns the comment. */public function post(): BelongsTo{ return $this->belongsTo(Post::class, 'foreign_key');}
If your parent model does not use id as its primary key, or you wish to find the associated model using a different column, you may pass a third argument to the belongsTo method specifying your parent table’s custom key:
/** * Get the post that owns the comment. */public function post(): BelongsTo{ return $this->belongsTo(Post::class, 'foreign_key', 'owner_key');}
Default Models
The belongsTo, hasOne, hasOneThrough, and morphOne relationships allow you to define a default model that will be returned if the given relationship is null. This pattern is often referred to as the Null Object pattern and can help remove conditional checks in your code. In the following example, the user relation will return an empty App\Models\User model if no user is attached to the Post model:
/** * Get the author of the post. */public function user(): BelongsTo{ return $this->belongsTo(User::class)->withDefault();}
To populate the default model with attributes, you may pass an array or closure to the withDefault method:
/** * Get the author of the post. */public function user(): BelongsTo{ return $this->belongsTo(User::class)->withDefault([ 'name' => 'Guest Author', ]);} /** * Get the author of the post. */public function user(): BelongsTo{ return $this->belongsTo(User::class)->withDefault(function (User $user, Post $post) { $user->name = 'Guest Author'; });}
Querying Belongs To Relationships
When querying for the children of a “belongs to” relationship, you may manually build the where clause to retrieve the corresponding Eloquent models:
use App\Models\Post; $posts = Post::where('user_id', $user->id)->get();
However, you may find it more convenient to use the whereBelongsTo method, which will automatically determine the proper relationship and foreign key for the given model:
$posts = Post::whereBelongsTo($user)->get();
You may also provide a collection instance to the whereBelongsTo method. When doing so, Laravel will retrieve models that belong to any of the parent models within the collection:
$users = User::where('vip', true)->get(); $posts = Post::whereBelongsTo($users)->get();
By default, Laravel will determine the relationship associated with the given model based on the class name of the model; however, you may specify the relationship name manually by providing it as the second argument to the whereBelongsTo method:
$posts = Post::whereBelongsTo($user, 'author')->get();
Has One Of Many
Sometimes a model may have many related models, yet you want to easily retrieve the “latest” or “oldest” related model of the relationship. For example, a User model may be related to many Order models, but you want to define a convenient way to interact with the most recent order the user has placed. You may accomplish this using the hasOne relationship type combined with the ofMany methods:
/** * Get the user's most recent order. */public function latestOrder(): HasOne{ return $this->hasOne(Order::class)->latestOfMany();}
Likewise, you may define a method to retrieve the “oldest”, or first, related model of a relationship:
/** * Get the user's oldest order. */public function oldestOrder(): HasOne{ return $this->hasOne(Order::class)->oldestOfMany();}
By default, the latestOfMany and oldestOfMany methods will retrieve the latest or oldest related model based on the model’s primary key, which must be sortable. However, sometimes you may wish to retrieve a single model from a larger relationship using a different sorting criteria.
For example, using the ofMany method, you may retrieve the user’s most expensive order. The ofMany method accepts the sortable column as its first argument and which aggregate function (min or max) to apply when querying for the related model:
/** * Get the user's largest order. */public function largestOrder(): HasOne{ return $this->hasOne(Order::class)->ofMany('price', 'max');}
Warning
Because PostgreSQL does not support executing theMAXfunction against UUID columns, it is not currently possible to use one-of-many relationships in combination with PostgreSQL UUID columns.
Advanced Has One Of Many Relationships
It is possible to construct more advanced “has one of many” relationships. For example, a Product model may have many associated Price models that are retained in the system even after new pricing is published. In addition, new pricing data for the product may be able to be published in advance to take effect at a future date via a published_at column.
So, in summary, we need to retrieve the latest published pricing where the published date is not in the future. In addition, if two prices have the same published date, we will prefer the price with the greatest ID. To accomplish this, we must pass an array to the ofMany method that contains the sortable columns which determine the latest price. In addition, a closure will be provided as the second argument to the ofMany method. This closure will be responsible for adding additional publish date constraints to the relationship query:
/** * Get the current pricing for the product. */public function currentPricing(): HasOne{ return $this->hasOne(Price::class)->ofMany([ 'published_at' => 'max', 'id' => 'max', ], function (Builder $query) { $query->where('published_at', '<', now()); });}
Has One Through
The “has-one-through” relationship defines a one-to-one relationship with another model. However, this relationship indicates that the declaring model can be matched with one instance of another model by proceeding through a third model.
For example, in a vehicle repair shop application, each Mechanic model may be associated with one Car model, and each Car model may be associated with one Owner model. While the mechanic and the owner have no direct relationship within the database, the mechanic can access the owner through the Car model. Let’s look at the tables necessary to define this relationship:
mechanics id - integer name - string cars id - integer model - string mechanic_id - integer owners id - integer name - string car_id - integer
Now that we have examined the table structure for the relationship, let’s define the relationship on the Mechanic model:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model;use Illuminate\Database\Eloquent\Relations\HasOneThrough; class Mechanic extends Model{ /** * Get the car's owner. */ public function carOwner(): HasOneThrough { return $this->hasOneThrough(Owner::class, Car::class); }}
The first argument passed to the hasOneThrough method is the name of the final model we wish to access, while the second argument is the name of the intermediate model.
Or, if the relevant relationships have already been defined on all of the models involved in the relationship, you may fluently define a “has-one-through” relationship by invoking the through method and supplying the names of those relationships. For example, if the Mechanic model has a cars relationship and the Car model has an owner relationship, you may define a “has-one-through” relationship connecting the mechanic and the owner like so:
// String based syntax...return $this->through('cars')->has('owner'); // Dynamic syntax...return $this->throughCars()->hasOwner();
Key Conventions
Typical Eloquent foreign key conventions will be used when performing the relationship’s queries. If you would like to customize the keys of the relationship, you may pass them as the third and fourth arguments to the hasOneThrough method. The third argument is the name of the foreign key on the intermediate model. The fourth argument is the name of the foreign key on the final model. The fifth argument is the local key, while the sixth argument is the local key of the intermediate model:
class Mechanic extends Model{ /** * Get the car's owner. */ public function carOwner(): HasOneThrough { return $this->hasOneThrough( Owner::class, Car::class, 'mechanic_id', // Foreign key on the cars table... 'car_id', // Foreign key on the owners table... 'id', // Local key on the mechanics table... 'id' // Local key on the cars table... ); }}
Or, as discussed earlier, if the relevant relationships have already been defined on all of the models involved in the relationship, you may fluently define a “has-one-through” relationship by invoking the through method and supplying the names of those relationships. This approach offers the advantage of reusing the key conventions already defined on the existing relationships:
// String based syntax...return $this->through('cars')->has('owner'); // Dynamic syntax...return $this->throughCars()->hasOwner();
Has Many Through
The “has-many-through” relationship provides a convenient way to access distant relations via an intermediate relation. For example, let’s assume we are building a deployment platform like Laravel Vapor. A Project model might access many Deployment models through an intermediate Environment model. Using this example, you could easily gather all deployments for a given project. Let’s look at the tables required to define this relationship:
projects id - integer name - string environments id - integer project_id - integer name - string deployments id - integer environment_id - integer commit_hash - string
Now that we have examined the table structure for the relationship, let’s define the relationship on the Project model:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model;use Illuminate\Database\Eloquent\Relations\HasManyThrough; class Project extends Model{ /** * Get all of the deployments for the project. */ public function deployments(): HasManyThrough { return $this->hasManyThrough(Deployment::class, Environment::class); }}
The first argument passed to the hasManyThrough method is the name of the final model we wish to access, while the second argument is the name of the intermediate model.
Or, if the relevant relationships have already been defined on all of the models involved in the relationship, you may fluently define a “has-many-through” relationship by invoking the through method and supplying the names of those relationships. For example, if the Project model has a environments relationship and the Environment model has a deployments relationship, you may define a “has-many-through” relationship connecting the project and the deployments like so:
// String based syntax...return $this->through('environments')->has('deployments'); // Dynamic syntax...return $this->throughEnvironments()->hasDeployments();
Though the Deployment model’s table does not contain a project_id column, the hasManyThrough relation provides access to a project’s deployments via $project->deployments. To retrieve these models, Eloquent inspects the project_id column on the intermediate Environment model’s table. After finding the relevant environment IDs, they are used to query the Deployment model’s table.
Key Conventions
Typical Eloquent foreign key conventions will be used when performing the relationship’s queries. If you would like to customize the keys of the relationship, you may pass them as the third and fourth arguments to the hasManyThrough method. The third argument is the name of the foreign key on the intermediate model. The fourth argument is the name of the foreign key on the final model. The fifth argument is the local key, while the sixth argument is the local key of the intermediate model:
class Project extends Model{ public function deployments(): HasManyThrough { return $this->hasManyThrough( Deployment::class, Environment::class, 'project_id', // Foreign key on the environments table... 'environment_id', // Foreign key on the deployments table... 'id', // Local key on the projects table... 'id' // Local key on the environments table... ); }}
Or, as discussed earlier, if the relevant relationships have already been defined on all of the models involved in the relationship, you may fluently define a “has-many-through” relationship by invoking the through method and supplying the names of those relationships. This approach offers the advantage of reusing the key conventions already defined on the existing relationships:
// String based syntax...return $this->through('environments')->has('deployments'); // Dynamic syntax...return $this->throughEnvironments()->hasDeployments();
Many To Many Relationships
Many-to-many relations are slightly more complicated than hasOne and hasMany relationships. An example of a many-to-many relationship is a user that has many roles and those roles are also shared by other users in the application. For example, a user may be assigned the role of “Author” and “Editor”; however, those roles may also be assigned to other users as well. So, a user has many roles and a role has many users.
Table Structure
To define this relationship, three database tables are needed: users, roles, and role_user. The role_user table is derived from the alphabetical order of the related model names and contains user_id and role_id columns. This table is used as an intermediate table linking the users and roles.
Remember, since a role can belong to many users, we cannot simply place a user_id column on the roles table. This would mean that a role could only belong to a single user. In order to provide support for roles being assigned to multiple users, the role_user table is needed. We can summarize the relationship’s table structure like so:
users id - integer name - string roles id - integer name - string role_user user_id - integer role_id - integer
Model Structure
Many-to-many relationships are defined by writing a method that returns the result of the belongsToMany method. The belongsToMany method is provided by the Illuminate\Database\Eloquent\Model base class that is used by all of your application’s Eloquent models. For example, let’s define a roles method on our User model. The first argument passed to this method is the name of the related model class:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model;use Illuminate\Database\Eloquent\Relations\BelongsToMany; class User extends Model{ /** * The roles that belong to the user. */ public function roles(): BelongsToMany { return $this->belongsToMany(Role::class); }}
Once the relationship is defined, you may access the user’s roles using the roles dynamic relationship property:
use App\Models\User; $user = User::find(1); foreach ($user->roles as $role) { // ...}
Since all relationships also serve as query builders, you may add further constraints to the relationship query by calling the roles method and continuing to chain conditions onto the query:
$roles = User::find(1)->roles()->orderBy('name')->get();
To determine the table name of the relationship’s intermediate table, Eloquent will join the two related model names in alphabetical order. However, you are free to override this convention. You may do so by passing a second argument to the belongsToMany method:
return $this->belongsToMany(Role::class, 'role_user');
In addition to customizing the name of the intermediate table, you may also customize the column names of the keys on the table by passing additional arguments to the belongsToMany method. The third argument is the foreign key name of the model on which you are defining the relationship, while the fourth argument is the foreign key name of the model that you are joining to:
return $this->belongsToMany(Role::class, 'role_user', 'user_id', 'role_id');
Defining The Inverse Of The Relationship
To define the “inverse” of a many-to-many relationship, you should define a method on the related model which also returns the result of the belongsToMany method. To complete our user / role example, let’s define the users method on the Role model:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model;use Illuminate\Database\Eloquent\Relations\BelongsToMany; class Role extends Model{ /** * The users that belong to the role. */ public function users(): BelongsToMany { return $this->belongsToMany(User::class); }}
As you can see, the relationship is defined exactly the same as its User model counterpart with the exception of referencing the App\Models\User model. Since we’re reusing the belongsToMany method, all of the usual table and key customization options are available when defining the “inverse” of many-to-many relationships.
Retrieving Intermediate Table Columns
As you have already learned, working with many-to-many relations requires the presence of an intermediate table. Eloquent provides some very helpful ways of interacting with this table. For example, let’s assume our User model has many Role models that it is related to. After accessing this relationship, we may access the intermediate table using the pivot attribute on the models:
use App\Models\User; $user = User::find(1); foreach ($user->roles as $role) { echo $role->pivot->created_at;}
Notice that each Role model we retrieve is automatically assigned a pivot attribute. This attribute contains a model representing the intermediate table.
By default, only the model keys will be present on the pivot model. If your intermediate table contains extra attributes, you must specify them when defining the relationship:
return $this->belongsToMany(Role::class)->withPivot('active', 'created_by');
If you would like your intermediate table to have created_at and updated_at timestamps that are automatically maintained by Eloquent, call the withTimestamps method when defining the relationship:
return $this->belongsToMany(Role::class)->withTimestamps();
Warning
Intermediate tables that utilize Eloquent’s automatically maintained timestamps are required to have bothcreated_atandupdated_attimestamp columns.
Customizing The pivot Attribute Name
As noted previously, attributes from the intermediate table may be accessed on models via the pivot attribute. However, you are free to customize the name of this attribute to better reflect its purpose within your application.
For example, if your application contains users that may subscribe to podcasts, you likely have a many-to-many relationship between users and podcasts. If this is the case, you may wish to rename your intermediate table attribute to subscription instead of pivot. This can be done using the as method when defining the relationship:
return $this->belongsToMany(Podcast::class) ->as('subscription') ->withTimestamps();
Once the custom intermediate table attribute has been specified, you may access the intermediate table data using the customized name:
$users = User::with('podcasts')->get(); foreach ($users->flatMap->podcasts as $podcast) { echo $podcast->subscription->created_at;}
Filtering Queries Via Intermediate Table Columns
You can also filter the results returned by belongsToMany relationship queries using the wherePivot, wherePivotIn, wherePivotNotIn, wherePivotBetween, wherePivotNotBetween, wherePivotNull, and wherePivotNotNull methods when defining the relationship:
return $this->belongsToMany(Role::class) ->wherePivot('approved', 1); return $this->belongsToMany(Role::class) ->wherePivotIn('priority', [1, 2]); return $this->belongsToMany(Role::class) ->wherePivotNotIn('priority', [1, 2]); return $this->belongsToMany(Podcast::class) ->as('subscriptions') ->wherePivotBetween('created_at', ['2020-01-01 00:00:00', '2020-12-31 00:00:00']); return $this->belongsToMany(Podcast::class) ->as('subscriptions') ->wherePivotNotBetween('created_at', ['2020-01-01 00:00:00', '2020-12-31 00:00:00']); return $this->belongsToMany(Podcast::class) ->as('subscriptions') ->wherePivotNull('expired_at'); return $this->belongsToMany(Podcast::class) ->as('subscriptions') ->wherePivotNotNull('expired_at');
Ordering Queries Via Intermediate Table Columns
You can order the results returned by belongsToMany relationship queries using the orderByPivot method. In the following example, we will retrieve all of the latest badges for the user:
return $this->belongsToMany(Badge::class) ->where('rank', 'gold') ->orderByPivot('created_at', 'desc');
Defining Custom Intermediate Table Models
If you would like to define a custom model to represent the intermediate table of your many-to-many relationship, you may call the using method when defining the relationship. Custom pivot models give you the opportunity to define additional behavior on the pivot model, such as methods and casts.
Custom many-to-many pivot models should extend the Illuminate\Database\Eloquent\Relations\Pivot class while custom polymorphic many-to-many pivot models should extend the Illuminate\Database\Eloquent\Relations\MorphPivot class. For example, we may define a Role model which uses a custom RoleUser pivot model:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model;use Illuminate\Database\Eloquent\Relations\BelongsToMany; class Role extends Model{ /** * The users that belong to the role. */ public function users(): BelongsToMany { return $this->belongsToMany(User::class)->using(RoleUser::class); }}
When defining the RoleUser model, you should extend the Illuminate\Database\Eloquent\Relations\Pivot class:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Relations\Pivot; class RoleUser extends Pivot{ // ...}
Warning
Pivot models may not use theSoftDeletestrait. If you need to soft delete pivot records consider converting your pivot model to an actual Eloquent model.
Custom Pivot Models And Incrementing IDs
If you have defined a many-to-many relationship that uses a custom pivot model, and that pivot model has an auto-incrementing primary key, you should ensure your custom pivot model class defines an incrementing property that is set to true.
/** * Indicates if the IDs are auto-incrementing. * * @var bool */public $incrementing = true;
Polymorphic Relationships
A polymorphic relationship allows the child model to belong to more than one type of model using a single association. For example, imagine you are building an application that allows users to share blog posts and videos. In such an application, a Comment model might belong to both the Post and Video models.
One To One (Polymorphic)
Table Structure
A one-to-one polymorphic relation is similar to a typical one-to-one relation; however, the child model can belong to more than one type of model using a single association. For example, a blog Post and a User may share a polymorphic relation to an Image model. Using a one-to-one polymorphic relation allows you to have a single table of unique images that may be associated with posts and users. First, let’s examine the table structure:
posts id - integer name - string users id - integer name - string images id - integer url - string imageable_id - integer imageable_type - string
Note the imageable_id and imageable_type columns on the images table. The imageable_id column will contain the ID value of the post or user, while the imageable_type column will contain the class name of the parent model. The imageable_type column is used by Eloquent to determine which “type” of parent model to return when accessing the imageable relation. In this case, the column would contain either App\Models\Post or App\Models\User.
Model Structure
Next, let’s examine the model definitions needed to build this relationship:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model;use Illuminate\Database\Eloquent\Relations\MorphTo; class Image extends Model{ /** * Get the parent imageable model (user or post). */ public function imageable(): MorphTo { return $this->morphTo(); }} use Illuminate\Database\Eloquent\Model;use Illuminate\Database\Eloquent\Relations\MorphOne; class Post extends Model{ /** * Get the post's image. */ public function image(): MorphOne { return $this->morphOne(Image::class, 'imageable'); }} use Illuminate\Database\Eloquent\Model;use Illuminate\Database\Eloquent\Relations\MorphOne; class User extends Model{ /** * Get the user's image. */ public function image(): MorphOne { return $this->morphOne(Image::class, 'imageable'); }}
Retrieving The Relationship
Once your database table and models are defined, you may access the relationships via your models. For example, to retrieve the image for a post, we can access the image dynamic relationship property:
use App\Models\Post; $post = Post::find(1); $image = $post->image;
You may retrieve the parent of the polymorphic model by accessing the name of the method that performs the call to morphTo. In this case, that is the imageable method on the Image model. So, we will access that method as a dynamic relationship property:
use App\Models\Image; $image = Image::find(1); $imageable = $image->imageable;
The imageable relation on the Image model will return either a Post or User instance, depending on which type of model owns the image.
Key Conventions
If necessary, you may specify the name of the “id” and “type” columns utilized by your polymorphic child model. If you do so, ensure that you always pass the name of the relationship as the first argument to the morphTo method. Typically, this value should match the method name, so you may use PHP’s __FUNCTION__ constant:
/** * Get the model that the image belongs to. */public function imageable(): MorphTo{ return $this->morphTo(__FUNCTION__, 'imageable_type', 'imageable_id');}
One To Many (Polymorphic)
Table Structure
A one-to-many polymorphic relation is similar to a typical one-to-many relation; however, the child model can belong to more than one type of model using a single association. For example, imagine users of your application can “comment” on posts and videos. Using polymorphic relationships, you may use a single comments table to contain comments for both posts and videos. First, let’s examine the table structure required to build this relationship:
posts id - integer title - string body - text videos id - integer title - string url - string comments id - integer body - text commentable_id - integer commentable_type - string
Model Structure
Next, let’s examine the model definitions needed to build this relationship:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model;use Illuminate\Database\Eloquent\Relations\MorphTo; class Comment extends Model{ /** * Get the parent commentable model (post or video). */ public function commentable(): MorphTo { return $this->morphTo(); }} use Illuminate\Database\Eloquent\Model;use Illuminate\Database\Eloquent\Relations\MorphMany; class Post extends Model{ /** * Get all of the post's comments. */ public function comments(): MorphMany { return $this->morphMany(Comment::class, 'commentable'); }} use Illuminate\Database\Eloquent\Model;use Illuminate\Database\Eloquent\Relations\MorphMany; class Video extends Model{ /** * Get all of the video's comments. */ public function comments(): MorphMany { return $this->morphMany(Comment::class, 'commentable'); }}
Retrieving The Relationship
Once your database table and models are defined, you may access the relationships via your model’s dynamic relationship properties. For example, to access all of the comments for a post, we can use the comments dynamic property:
use App\Models\Post; $post = Post::find(1); foreach ($post->comments as $comment) { // ...}
You may also retrieve the parent of a polymorphic child model by accessing the name of the method that performs the call to morphTo. In this case, that is the commentable method on the Comment model. So, we will access that method as a dynamic relationship property in order to access the comment’s parent model:
use App\Models\Comment; $comment = Comment::find(1); $commentable = $comment->commentable;
The commentable relation on the Comment model will return either a Post or Video instance, depending on which type of model is the comment’s parent.
One Of Many (Polymorphic)
Sometimes a model may have many related models, yet you want to easily retrieve the “latest” or “oldest” related model of the relationship. For example, a User model may be related to many Image models, but you want to define a convenient way to interact with the most recent image the user has uploaded. You may accomplish this using the morphOne relationship type combined with the ofMany methods:
/** * Get the user's most recent image. */public function latestImage(): MorphOne{ return $this->morphOne(Image::class, 'imageable')->latestOfMany();}
Likewise, you may define a method to retrieve the “oldest”, or first, related model of a relationship:
/** * Get the user's oldest image. */public function oldestImage(): MorphOne{ return $this->morphOne(Image::class, 'imageable')->oldestOfMany();}
By default, the latestOfMany and oldestOfMany methods will retrieve the latest or oldest related model based on the model’s primary key, which must be sortable. However, sometimes you may wish to retrieve a single model from a larger relationship using a different sorting criteria.
For example, using the ofMany method, you may retrieve the user’s most “liked” image. The ofMany method accepts the sortable column as its first argument and which aggregate function (min or max) to apply when querying for the related model:
/** * Get the user's most popular image. */public function bestImage(): MorphOne{ return $this->morphOne(Image::class, 'imageable')->ofMany('likes', 'max');}
Note
It is possible to construct more advanced “one of many” relationships. For more information, please consult the has one of many documentation.
Many To Many (Polymorphic)
Table Structure
Many-to-many polymorphic relations are slightly more complicated than “morph one” and “morph many” relationships. For example, a Post model and Video model could share a polymorphic relation to a Tag model. Using a many-to-many polymorphic relation in this situation would allow your application to have a single table of unique tags that may be associated with posts or videos. First, let’s examine the table structure required to build this relationship:
posts id - integer name - string videos id - integer name - string tags id - integer name - string taggables tag_id - integer taggable_id - integer taggable_type - string
Note
Before diving into polymorphic many-to-many relationships, you may benefit from reading the documentation on typical many-to-many relationships.
Model Structure
Next, we’re ready to define the relationships on the models. The Post and Video models will both contain a tags method that calls the morphToMany method provided by the base Eloquent model class.
The morphToMany method accepts the name of the related model as well as the “relationship name”. Based on the name we assigned to our intermediate table name and the keys it contains, we will refer to the relationship as “taggable”:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model;use Illuminate\Database\Eloquent\Relations\MorphToMany; class Post extends Model{ /** * Get all of the tags for the post. */ public function tags(): MorphToMany { return $this->morphToMany(Tag::class, 'taggable'); }}
Defining The Inverse Of The Relationship
Next, on the Tag model, you should define a method for each of its possible parent models. So, in this example, we will define a posts method and a videos method. Both of these methods should return the result of the morphedByMany method.
The morphedByMany method accepts the name of the related model as well as the “relationship name”. Based on the name we assigned to our intermediate table name and the keys it contains, we will refer to the relationship as “taggable”:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model;use Illuminate\Database\Eloquent\Relations\MorphToMany; class Tag extends Model{ /** * Get all of the posts that are assigned this tag. */ public function posts(): MorphToMany { return $this->morphedByMany(Post::class, 'taggable'); } /** * Get all of the videos that are assigned this tag. */ public function videos(): MorphToMany { return $this->morphedByMany(Video::class, 'taggable'); }}
Retrieving The Relationship
Once your database table and models are defined, you may access the relationships via your models. For example, to access all of the tags for a post, you may use the tags dynamic relationship property:
use App\Models\Post; $post = Post::find(1); foreach ($post->tags as $tag) { // ...}
You may retrieve the parent of a polymorphic relation from the polymorphic child model by accessing the name of the method that performs the call to morphedByMany. In this case, that is the posts or videos methods on the Tag model:
use App\Models\Tag; $tag = Tag::find(1); foreach ($tag->posts as $post) { // ...} foreach ($tag->videos as $video) { // ...}
(本文超出站点单文档体积上限,已按小节截断)
