Movatterモバイル変換


[0]ホーム

URL:


Skip to main content
🧑🏽‍🔬 We're testing new AI and search tools ondocs-next.strapi.io! Feel free to have a look andshare your feedback
  • API calls
  • CRON jobs
  • Environment variables
  • Features
  • Middlewares
  • Plugins
  • Server
  • Models

    As Strapi is a headless Content Management System (CMS), creating a content structure for the content is one of the most important aspects of using the software. Models define a representation of the content structure.

    There are 2 different types of models in Strapi:

    • content-types, which can be collection types or single types, depending on how many entries they manage,
    • and components that are content structures re-usable in multiple content-types.

    If you are just starting out, it is convenient to generate some models with theContent-type Builder directly in the admin panel. The user interface takes over a lot of validation tasks and showcases all the options available to create the content's content structure. The generated model mappings can then be reviewed at the code level using this documentation.

    Model creation

    Content-types and components models are created and stored differently.

    Content-types

    Content-types in Strapi can be created:

    The content-types use the following files:

    • schema.json for the model'sschema definition. (generated automatically, when creating content-type with either method)
    • lifecycles.js forlifecycle hooks. This file must be created manually.

    These models files are stored in./src/api/[api-name]/content-types/[content-type-name]/, and any JavaScript or JSON file found in these folders will be loaded as a content-type's model (seeproject structure).

    Note

    InTypeScript-enabled projects, schema typings can be generated using thets:generate-types command.

    Components

    Component models can't be created with CLI tools. Use theContent-type Builder or create them manually.

    Components models are stored in the./src/components folder. Every component has to be inside a subfolder, named after the category the component belongs to (seeproject structure).

    Model schema

    Theschema.json file of a model consists of:

    • settings, such as the kind of content-type the model represents or the table name in which the data should be stored,
    • information, mostly used to display the model in the admin panel and access it through the REST and GraphQL APIs,
    • attributes, which describe the content structure of the model,
    • andoptions used to defined specific behaviors on the model.

    Model settings

    General settings for the model can be configured with the following parameters:

    ParameterTypeDescription
    collectionNameStringDatabase table name in which the data should be stored
    kind

    Optional,
    only for content-types
    StringDefines if the content-type is:
    • a collection type (collectionType)
    • or a single type (singleType)
    // ./src/api/[api-name]/content-types/restaurant/schema.json

    {
    "kind":"collectionType",
    "collectionName":"Restaurants_v1",
    }

    Model information

    Theinfo key in the model's schema describes information used to display the model in the admin panel and access it through the Content API. It includes the following parameters:

    ParameterTypeDescription
    displayNameStringDefault name to use in the admin panel
    singularNameStringSingular form of the content-type name.
    Used to generate the API routes and databases/tables collection.

    Should be kebab-case.
    pluralNameStringPlural form of the content-type name.
    Used to generate the API routes and databases/tables collection.

    Should be kebab-case.
    descriptionStringDescription of the model
    ./src/api/[api-name]/content-types/restaurant/schema.json

    "info":{
    "displayName":"Restaurant",
    "singularName":"restaurant",
    "pluralName":"restaurants",
    "description":""
    },

    Model attributes

    The content structure of a model consists of a list of attributes. Each attribute has atype parameter, which describes its nature and defines the attribute as a simple piece of data or a more complex structure used by Strapi.

    Many types of attributes are available:

    • scalar types (e.g. strings, dates, numbers, booleans, etc.),
    • Strapi-specific types, such as:

    Thetype parameter of an attribute should be one of the following values:

    Type categoriesAvailable types
    String types
    • string
    • text
    • richtext
    • enumeration
    • email
    • password
    • uid
    Date types
    • date
    • time
    • datetime
    • timestamp
    Number types
    • integer
    • biginteger
    • float
    • decimal
    Other generic types
    • boolean
    • json
    Special types unique to Strapi
    Internationalization (i18n)-related types

    Can only be used if thei18n is enabled on the content-type
    • locale
    • localizations

    Validations

    Basic validations can be applied to attributes using the following parameters:

    ParameterTypeDescriptionDefault
    requiredBooleanIftrue, adds a required validator for this propertyfalse
    maxIntegerChecks if the value is greater than or equal to the given maximum-
    minIntegerChecks if the value is less than or equal to the given minimum-
    minLengthIntegerMinimum number of characters for a field input value-
    maxLengthIntegerMaximum number of characters for a field input value-
    privateBooleanIftrue, the attribute will be removed from the server response.

    💡 This is useful to hide sensitive data.
    false
    configurableBooleanIffalse, the attribute isn't configurable from the Content-type Builder plugin.true
    ./src/api/[api-name]/content-types/restaurant/schema.json

    {
    // ...
    "attributes":{
    "title":{
    "type":"string",
    "minLength":3,
    "maxLength":99,
    "unique":true
    },
    "description":{
    "default":"My description",
    "type":"text",
    "required":true
    },
    "slug":{
    "type":"uid",
    "targetField":"title"
    }
    // ...
    }
    }

    Database validations and settings

    🚧 This API is considered experimental.

    These settings should be reserved to an advanced usage, as they might break some features. There are no plans to make these settings stable.

    Database validations and settings are custom options passed directly onto thetableBuilder Knex.js function during schema migrations. Database validations allow for an advanced degree of control for setting custom column settings. The following options are set in acolumn: {} object per attribute:

    ParameterTypeDescriptionDefault
    namestringChanges the name of the column in the database-
    defaultTostringSets the databasedefaultTo, typically used withnotNullable-
    notNullablebooleanSets the databasenotNullable, ensures that columns cannot be nullfalse
    unsignedbooleanOnly applies to number columns, removes the ability to go negative but doubles maximum lengthfalse
    uniquebooleanEnforces database level unique, caution when using with draft & publish featurefalse
    typestringChanges the database type, iftype has arguments, you should pass them inargs-
    argsarrayArguments passed into the Knex.js function that changes things liketype[]
    ./src/api/[api-name]/content-types/restaurant/schema.json

    {
    // ...
    "attributes":{
    "title":{
    "type":"string",
    "minLength":3,
    "maxLength":99,
    "unique":true,
    "column":{
    "unique":true// enforce database unique also
    }
    },
    "description":{
    "default":"My description",
    "type":"text",
    "required":true,
    "column":{
    "defaultTo":"My description",// set database level default
    "notNullable":true// enforce required at database level, even for drafts
    }
    },
    "rating":{
    "type":"decimal",
    "default":0,
    "column":{
    "defaultTo":0,
    "type":"decimal",// using the native decimal type but allowing for custom precision
    "args":[
    6,1// using custom precision and scale
    ]
    }
    }
    // ...
    }
    }

    uid type

    Theuid type is used to automatically prefill the field value in the admin panel with a unique identifier (UID) (e.g. slugs for articles) based on 2 optional parameters:

    • targetField (string): If used, the value of the field defined as a target is used to auto-generate the UID.
    • options (string): If used, the UID is generated based on a set of options passed tothe underlying `uid` generator. The resultinguid must match the following regular expression pattern:/^[A-Za-z0-9-_.~]*$.

    Relations

    Relations link content-types together. Relations are explicitly defined in theattributes of a model withtype: 'relation' and accept the following additional parameters:

    ParameterDescription
    relationThe type of relation among these values:
    • oneToOne
    • oneToMany
    • manyToOne
    • manyToMany
    targetAccepts a string value as the name of the target content-type
    mappedBy andinversedBy

    Optional
    In bidirectional relations, the owning side declares theinversedBy key while the inversed side declares themappedBy key
    • One-to-one
    • One-to-Many
    • Many-to-One
    • Many-to-Many

    One-to-One relationships are useful when one entry can be linked to only one other entry.

    They can be unidirectional or bidirectional. In unidirectional relationships, only one of the models can be queried with its linked item.

    Unidirectional use case example:
    • A blog article belongs to a category.
    • Querying an article can retrieve its category,
    • but querying a category won't retrieve the owned article.
    ./src/api/[api-name]/content-types/article/schema.json

    // …
    attributes:{
    category:{
    type: 'relation',
    relation: 'oneToOne',
    target: 'category',
    },
    },
    // …
    Bidirectional use case example:
    • A blog article belongs to a category.
    • Querying an article can retrieve its category,
    • and querying a category also retrieves its owned article.
    ./src/api/[api-name]/content-types/article/schema.json

    // …
    attributes:{
    category:{
    type: 'relation',
    relation: 'oneToOne',
    target: 'category',
    inversedBy: 'article',
    },
    },
    // …

    ./src/api/[api-name]/content-types/category/schema.json

    // …
    attributes:{
    article:{
    type: 'relation',
    relation: 'oneToOne',
    target: 'article',
    mappedBy: 'category',
    },
    },
    // …

    Custom fields

    Custom fields extend Strapi’s capabilities by adding new types of fields to content-types. Custom fields are explicitly defined in theattributes of a model withtype: customField.

    Custom fields' attributes also show the following specificities:

    • acustomField attribute whose value acts as a unique identifier to indicate which registered custom field should be used. Its value follows:
      • either theplugin::plugin-name.field-name format if a plugin created the custom field
      • or theglobal::field-name format for a custom field specific to the current Strapi application
    • and additional parameters depending on what has been defined when registering the custom field (seecustom fields documentation).
    ./src/api/[apiName]/[content-type-name]/content-types/schema.json

    {
    // …
    "attributes":{
    "attributeName":{// attributeName would be replaced by the actual attribute name
    "type":"customField",
    "customField":"plugin::color-picker.color",
    "options":{
    "format":"hex"
    }
    }
    }
    // …
    }

    Components

    Component fields create a relation between a content-type and a component structure. Components are explicitly defined in theattributes of a model withtype: 'component' and accept the following additional parameters:

    ParameterTypeDescription
    repeatableBooleanCould betrue orfalse depending on whether the component is repeatable or not
    componentStringDefine the corresponding component, following this format:
    <category>.<componentName>
    ./src/api/[apiName]/restaurant/content-types/schema.json

    {
    "attributes":{
    "openinghours":{
    "type":"component",
    "repeatable":true,
    "component":"restaurant.openinghours"
    }
    }
    }

    Dynamic zones

    Dynamic zones create a flexible space in which to compose content, based on a mixed list ofcomponents.

    Dynamic zones are explicitly defined in theattributes of a model withtype: 'dynamiczone'. They also accept acomponents array, where each component should be named following this format:<category>.<componentName>.

    ./src/api/[api-name]/content-types/article/schema.json

    {
    "attributes":{
    "body":{
    "type":"dynamiczone",
    "components":["article.slider","article.content"]
    }
    }
    }

    Model options

    Theoptions key is used to define specific behaviors and accepts the following parameter:

    ParameterTypeDescription
    privateAttributesArray of stringsAllows treating a set of attributes as private, even if they're not actually defined as attributes in the model. It could be used to remove them from API responses timestamps.

    TheprivateAttributes defined in the model are merged with theprivateAttributes defined in the global Strapi configuration.
    draftAndPublishBooleanEnables the draft and publish feature.

    Default value:true (false if the content-type is created from the interactive CLI).
    populateCreatorFieldsBooleanPopulatescreatedBy andupdatedBy fields in responses returned by the REST API (seeguide for more details).

    Default value:false.
    ./src/api/[api-name]/content-types/restaurant/schema.json

    {
    "options":{
    "privateAttributes":["id","createdAt"],
    "draftAndPublish":true
    }
    }

    Lifecycle hooks

    Lifecycle hooks are functions that get triggered when Strapi queries are called. They are triggered automatically when managing content through the administration panel or when developing custom code usingqueries·

    Lifecycle hooks can be customized declaratively or programmatically.

    Caution

    Lifecycles hooks are not triggered when using directly theknex library instead of Strapi functions.

    Document Service API: lifecycles and middlewares

    The Document Service API triggers various database lifecycle hooks based on which method is called. For a complete reference, seeDocument Service API: Lifecycle hooks. Bulk actions lifecycles (createMany,updateMany,deleteMany) will never be triggered by a Document Service API method.Document Service middlewares can be implemented too.

    Available lifecycle events

    The following lifecycle events are available:

    • beforeCreate
    • beforeCreateMany
    • afterCreate
    • afterCreateMany
    • beforeUpdate
    • beforeUpdateMany
    • afterUpdate
    • afterUpdateMany
    • beforeDelete
    • beforeDeleteMany
    • afterDelete
    • afterDeleteMany
    • beforeCount
    • afterCount
    • beforeFindOne
    • afterFindOne
    • beforeFindMany
    • afterFindMany

    Hookevent object

    Lifecycle hooks are functions that take anevent parameter, an object with the following keys:

    KeyTypeDescription
    actionStringLifecycle event that has been triggered (seelist)
    modelArray of strings (uid)An array of uids of the content-types whose events will be listened to.
    If this argument is not supplied, events are listened on all content-types.
    paramsObjectAccepts the following parameters:
    • data
    • select
    • where
    • orderBy
    • limit
    • offset
    • populate
    resultObjectOptional, only available withafterXXX events

    Contains the result of the action.
    stateObjectQuery state, can be used to share state betweenbeforeXXX andafterXXX events of a query.

    Declarative and programmatic usage

    To configure a content-type lifecycle hook, create alifecycles.js file in the./src/api/[api-name]/content-types/[content-type-name]/ folder.

    Each event listener is called sequentially. They can be synchronous or asynchronous.

    • JavaScript
    • TypeScript
    ./src/api/[api-name]/content-types/[content-type-name]/lifecycles.js

    module.exports={
    beforeCreate(event){
    const{ data, where, select, populate}= event.params;

    // let's do a 20% discount everytime
    event.params.data.price= event.params.data.price*0.8;
    },

    afterCreate(event){
    const{ result, params}= event;

    // do something to the result;
    },
    };

    Using the database layer API, it's also possible to register a subscriber and listen to events programmatically:

    ./src/index.js
    module.exports={
    asyncbootstrap({ strapi}){
    // registering a subscriber
    strapi.db.lifecycles.subscribe({
    models:[],// optional;

    beforeCreate(event){
    const{ data, where, select, populate}= event.params;

    event.state='doStuffAfterWards';
    },

    afterCreate(event){
    if(event.state==='doStuffAfterWards'){
    }

    const{ result, params}= event;

    // do something to the result
    },
    });

    // generic subscribe for generic handling
    strapi.db.lifecycles.subscribe((event)=>{
    if(event.action==='beforeCreate'){
    // do something
    }
    });
    }
    }

    [8]ページ先頭

    ©2009-2025 Movatter.jp