> For the complete documentation index, see [llms.txt](https://quick.ortusbooks.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://quick.ortusbooks.com/13.0.0/guide/getting-started/creating-new-entities.md).

# Creating New Entities

## save

New Quick entities can be created and persisted to the database by creating a new entity instance, setting the attributes on the entity, and then calling the `save` method.

```javascript
var user = getInstance( "User" );
user.setUsername( "JaneDoe" );
user.setEmail( "jane@example.com" );
user.setPassword( "mypass1234" );
user.save();
```

When we call `save`, the record is persisted from the database and the primary key is set to the auto-generated value (if any).

Quick can also [maintain timestamps](/13.0.0/guide/getting-started/automatic-timestamps.md) and [refresh database-generated attributes](/13.0.0/guide/getting-started/defining-an-entity.md#refresh-on-save) as part of the same save lifecycle.

We can shortcut the setters above using a `fill` method.

## fill

Fills an entity from a struct of values.

| Name                        | Type          | Required | Default | Description                                                                                                        |
| --------------------------- | ------------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------ |
| attributes                  | struct        | `false`  | `{}`    | A struct of key / value pairs to fill in to the new entity.                                                        |
| ignoreNonExistentAttributes | boolean       | `false`  | `false` | If true, does not throw an exception if an attribute does not exist. Instead, it skips the non-existent attribute. |
| include                     | list or array | `false`  | `[]`    | List or array of keys to include when filling. All others will be ignored.                                         |
| exclude                     | list or array | `false`  | `[]`    | List or array of keys to exclude when filling. All others will be filled.                                          |

Sets attributes data from a struct of key / value pairs. This method does the following, in order:

1. Guard against read-only attributes.
2. Attempt to call a relationship setter.
3. Call custom attribute setters for persistent attributes.
4. Fill non-persistent properties explicitly marked [`fillable="true"`](/13.0.0/guide/getting-started/defining-an-entity.md#persistent).
5. Throw an error if an attribute does not exist (if `ignoreNonExistentAttributes` is `false`, which is the default).

```javascript
var user = getInstance( "User" );
user.fill( {
    "username": "JaneDoe",
    "email": "jane@example.com",
    "password": "mypass1234"
} );
user.save();
```

On a new entity, relationship values can be supplied as related entities or structs. Structs are filled into new related entity instances.

```javascript
var user = getInstance( "User" ).fill( {
    "username" : "JaneDoe",
    "posts" : [
        { "title" : "First post" },
        getInstance( "Post" ).fill( { "title" : "Second post" } )
    ]
} );
```

This only assigns the in-memory relationship. Saving the parent does not automatically persist the related entities; use the relationship's persistence methods explicitly.

## populate

| Name                        | Type    | Required | Default | Description                                                                                                        |
| --------------------------- | ------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------ |
| attributes                  | struct  | `false`  | `{}`    | A struct of key / value pairs to fill in to the new entity.                                                        |
| ignoreNonExistentAttributes | boolean | `false`  | `false` | If true, does not throw an exception if an attribute does not exist. Instead, it skips the non-existent attribute. |

Populate is simply an alias for `fill`. Use whichever one suits you best.

## create

| Name                        | Type    | Required | Default | Description                                                                                                        |
| --------------------------- | ------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------ |
| attributes                  | struct  | `false`  | `{}`    | A struct of key / value pairs to fill in to the new entity.                                                        |
| ignoreNonExistentAttributes | boolean | `false`  | `false` | If true, does not throw an exception if an attribute does not exist. Instead, it skips the non-existent attribute. |
| options                     | struct  | `false`  | `{}`    | Options passed to `queryExecute` when saving the entity.                                                           |

Creates a new entity with the given attributes and then saves the entity.

```javascript
var user = getInstance( "User" ).create( {
    "username": "JaneDoe",
    "email": "jane@example.com",
    "password": "mypass1234"
} );
```

There is no need to call `save` when using the `create` method.

## createAll

Creates and saves one entity for each struct in an array and returns the entities in the model's configured collection type.

| Name                        | Type    | Required | Default | Description                                     |
| --------------------------- | ------- | -------- | ------- | ----------------------------------------------- |
| attributes                  | array   | `false`  | `[]`    | An array of attribute structs to create.        |
| ignoreNonExistentAttributes | boolean | `false`  | `false` | If true, skips attributes that do not exist.    |
| options                     | struct  | `false`  | `{}`    | Options passed to `queryExecute` for each save. |

```javascript
var users = getInstance( "User" ).createAll( [
    { "username" : "JaneDoe", "email" : "jane@example.com" },
    { "username" : "JohnDoe", "email" : "john@example.com" }
] );
```

Each entity is saved independently, so casts, generated keys, automatic timestamps, and entity lifecycle events behave exactly as they do for `create()`.

## firstOrNew

| Name                        | Type    | Required | Default | Description                                                                                                               |
| --------------------------- | ------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------- |
| attributes                  | struct  | `false`  | `{}`    | A struct of attributes to restrict the query. If no entity is found the attributes are filled on the new entity returned. |
| newAttributes               | struct  | `false`  | `{}`    | A struct of attributes to fill on the new entity if no entity is found. These attributes are combined with `attributes`.  |
| ignoreNonExistentAttributes | boolean | `false`  | `false` | If true, does not throw an exception if an attribute does not exist. Instead, it skips the non-existent attribute.        |

Finds the first matching record or returns an unloaded new entity.

```javascript
var user = getInstance( "User" )
    .firstOrNew( { "username": rc.username } );
```

## firstOrCreate

| Name                        | Type    | Required | Default | Description                                                                                                                  |
| --------------------------- | ------- | -------- | ------- | ---------------------------------------------------------------------------------------------------------------------------- |
| attributes                  | struct  | `false`  | `{}`    | A struct of attributes to restrict the query. If no entity is found the attributes are filled on the new entity created.     |
| newAttributes               | struct  | `false`  | `{}`    | A struct of attributes to fill on the created entity if no entity is found. These attributes are combined with `attributes`. |
| ignoreNonExistentAttributes | boolean | `false`  | `false` | If true, does not throw an exception if an attribute does not exist. Instead, it skips the non-existent attribute.           |

Finds the first matching record or creates a new entity.

```javascript
var user = getInstance( "User" )
    .firstOrCreate( { "username": rc.username } );
```

## findOrNew

| Name                        | Type    | Required | Default | Description                                                                                                        |
| --------------------------- | ------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------ |
| id                          | any     | `true`   |         | The id value to find.                                                                                              |
| attributes                  | struct  | `false`  | `{}`    | A struct of attributes to fill on the new entity if no entity is found.                                            |
| ignoreNonExistentAttributes | boolean | `false`  | `false` | If true, does not throw an exception if an attribute does not exist. Instead, it skips the non-existent attribute. |

Returns the entity with the id value as the primary key. If no record is found, it returns a new unloaded entity.

```javascript
var user = getInstance( "User" ).findOrNew(
    9999,
      {
              "firstName" : "doesnt",
              "lastName"  : "exist"
      }
);
```

## findOrCreate

| Name                        | Type    | Required | Default | Description                                                                                                        |
| --------------------------- | ------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------ |
| id                          | any     | `true`   |         | The id value to find.                                                                                              |
| attributes                  | struct  | `false`  | `{}`    | A struct of attributes to use when creating the new entity if no entity is found.                                  |
| ignoreNonExistentAttributes | boolean | `false`  | `false` | If true, does not throw an exception if an attribute does not exist. Instead, it skips the non-existent attribute. |

Returns the entity with the id value as the primary key. If no record is found, it returns a newly created entity.

```javascript
var user = getInstance( "User" ).findOrCreate(
    9999,
      {
        "username"  : "doesntexist",
              "firstName" : "doesnt",
              "lastName"  : "exist",
              "password"  : "secret"
      }
);
```

## updateOrCreate

| Name                        | Type    | Required | Default | Description                                                                                                              |
| --------------------------- | ------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------ |
| attributes                  | struct  | `false`  | `{}`    | A struct of attributes to restrict the query. If no entity is found the attributes are filled on the new entity created. |
| newAttributes               | struct  | `false`  | `{}`    | A struct of attributes to update on the found entity or the new entity if no entity is found.                            |
| ignoreNonExistentAttributes | boolean | `false`  | `false` | If true, does not throw an exception if an attribute does not exist. Instead, it skips the non-existent attribute.       |

Updates an existing record or creates a new record with the given attributes.

```javascript
var user = getInstance( "User" ).updateOrCreate( {
    "username": "newuser"
} );
```

## Hydration Methods

Hydration is a term to describe filling an entity with a struct of data and then marking it as loaded, without doing any database queries. For example, this might be useful when hydrating a user from session data instead of doing a query every request.

### hydrate

| Name                        | Type    | Required | Default | Description                                                                                                        |
| --------------------------- | ------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------ |
| attributes                  | struct  | `false`  | `{}`    | A struct of key / value pairs to fill in to the entity.                                                            |
| ignoreNonExistentAttributes | boolean | `false`  | `false` | If true, does not throw an exception if an attribute does not exist. Instead, it skips the non-existent attribute. |

Hyrdates an entity from a struct of data. Hydrating an entity fills the entity and then marks it as loaded.

If the entity's keys are not included in the struct of data, a `MissingHydrationKey` is thrown.

```javascript
var user = getInstance( "User" ).hydrate( {
    "id": 4,
    "username": "JaneDoe",
    "email": "jane@example.com",
    "password": "mypass1234"
} );

user.isLoaded(); // true
```

### hydrateAll

| Name                        | Type    | Required | Default | Description                                                                                                        |
| --------------------------- | ------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------ |
| mementos                    | array   | `false`  | `[]`    | An array of structs to hydrate into entities.                                                                      |
| ignoreNonExistentAttributes | boolean | `false`  | `false` | If true, does not throw an exception if an attribute does not exist. Instead, it skips the non-existent attribute. |

Hydrates a new collection of entities from an array of structs.

```javascript
var users = getInstance( "User" ).hydrateAll( [
    {
        "id": 3,
        "username": "JohnDoe",
        "email": "john@example.com",
        "password": "mypass4321"
    },
    {
        "id": 4,
        "username": "JaneDoe",
        "email": "jane@example.com",
        "password": "mypass1234"
    }
] );
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://quick.ortusbooks.com/13.0.0/guide/getting-started/creating-new-entities.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
