# Models

Each database table has a corresponding "Model" which is used to interact with that table. Models allow you to query for data in your tables, as well as insert new records into the table.

Before getting started, be sure to configure a database connection in `config/env.json`. For more information on configuring your database, check out the [configuration](https://frameworkatom.github.io/#line3) documentation.

## **Defining Models**

To get started, let's create an model. Models typically live in the `app/models` directory, but you are free to place them anywhere that can be auto-loaded according to your `composer.json` file. All models extend `Atom\Database\Model` class.

The easiest way to create a model instance is using the `m:del` Atom command:

```
php atom g:del Post

or

php atom generate:model Post
```

## **Model Conventions**

Now, let's look at an example `Post` model, which we will use to retrieve and store information from our `posts` database table:

```php
<?php

namespace App\Models;

use Atom\Database\Model;


class Post extends Model
{
    //
}
```

### **Table Names**

Note that we did not tell Atom which table to use for our `Post` model. By convention, the "snake case", plural name of the class will be used as the table name unless another name is explicitly specified. So, in this case, Atom will assume the `Post` model stores records in the `posts` table. You may specify a custom table by defining a `$table_name` property on your model:

```php
<?php

namespace App\Models;

use Atom\Database\Model;


class Post extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table_name = 'my_posts';
}
```

### **Primary Keys**

Atom will also assume that each table has a primary key column named `id`. You may define a protected `$primaryKey`property to override this convention.

### **Timestamps**

By default, Atom doesn't expects `created_at` and `updated_at` columns to exist on your tables. If you wish to have these columns automatically managed by Atom, set the `$timestamps` property on your model to `true`:

```php
<?php

namespace App\Models;

use Atom\Database\Model;


class Post extends Model
{
    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    protected $timestamps = true;
}
```

## **Retrieving Models**

Once you have created a model and its associated database table, you are ready to start retrieving data from your database. Think of each Atom model as a powerful query builder allowing you to fluently query the database table associated with the model. For example:

```php
<?php

$posts = App\Models\Post::all();

foreach ($posts as $post) {
    echo $post->name;
}
```

## **Retrieving Single Models**

Of course, in addition to retrieving all of the records for a given table, you may also retrieve single records using `find` or `where`. Instead of returning a collection of models, these methods return a single model instance:

```php
// Retrieve a model by its primary key...
$post = App\Models\Post::find(1);

// Retrieve the first model matching the query constraints...
$post = App\Models\Post::where('active', 1);
```

## **Inserting, Updating & Deleting Models**

### **Inserts**

To create a new record in the database, create a new model instance, set attributes on the model, then call the `save`method:

```php
<?php

namespace App\Controllers;

use App\Models\Post;

class PostController
{
    /**
     * Create a new post instance.
     *
     * @return void
     */
    public function store()
    {
        $post = new Post;

        $post->title = request('title');

        $post->save();
    }
}
```

In this example, we assign the `title` parameter from the incoming HTTP request to the `title` attribute of the `App\Models\Post` model instance. When we call the `save` method, a record will be inserted into the database. The `created_at` and `updated_at` timestamps will automatically be set when the save method is called, so there is no need to set them manually.

### **Updates**

To update a model, you should retrieve it, set any attributes you wish to update, and then call the `update` method. Again, the `updated_at` timestamp will automatically be updated, so there is no need to manually set its value:

```php
$post = App\Models\Post::find(1);

$post->title = 'New Post Title';

$post->update();
```

### **Deletes**

To delete a model, call the `delete` method on a model instance:

```php
$post = App\Models\Post::find(1);

$post->delete();
```


---

# Agent Instructions: 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:

```
GET https://atomframework.gitbook.io/docs/basics/models.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
