Model Relationships
Blueprint also allows you to define many of the relationships available within Laravel, including: belongsTo
, hasOne
, hasMany
, and belongsToMany
.
In fact, the belongsTo
relationship is automatically generated for any column defined with the id
column type.
To define one of the additional relationships, you may add a relationships
section to your model definition. Within this section, you specify the relationship type followed by a comma separated list of model names.
For example, the following definition adds some common relationships to a Post
model:
models:
Post:
title: string:400
published_at: timestamp nullable
relationships:
hasMany: Comment
belongsToMany: Media, Site
belongsTo: \Spatie\LaravelPermission\Models\Role
While you may specify the relationships
anywhere within the model section, Blueprint recommends doing so at the bottom.
For each of these relationships, Blueprint will add the respective Eloquent relationship method within the generated model class. In addition, Blueprint will automatically generate the "pivot table" migration for any belongsToMany
relationship.
To specify a model which is not part of your application, you may provide the fully qualified class name. Be sure to include the initial \
(backslash). For example, \Spatie\LaravelPermission\Models\Role
.