Models
Dernière mise à jour
Cet article vous a-t-il été utile ?
Dernière mise à jour
Cet article vous a-t-il été utile ?
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 documentation.
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:
Now, let's look at an example Post
model, which we will use to retrieve and store information from our posts
database table:
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:
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.
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
:
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:
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:
To create a new record in the database, create a new model instance, set attributes on the model, then call the save
method:
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.
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:
To delete a model, call the delete
method on a model instance: