getting-started
Getting Started
[[toc]]
Introduction
Goravel provides a very easy-to-use way to interact with databases, Developers can use facades.Orm()
to operate. Currently, Goravel provides official support for the following four databases:
MySQL 5.7+
PostgreSQL 9.6+
SQLite 3.8.8+
SQL Server 2017+
Before starting, please configure the database in the .env
file and confirm the default configuration of config/database.go
.
Configuration
The configuration of databases is in the config/database.go
file. You can configure all database connections in this file and specify the default database connection. Most of configuration in this file is based on the project's environment variables, and provides examples of database configurations supported by Goravel.
Read & Write Connections
Sometimes you may wish to use one database connection for SELECT
statements, and another for INSERT
, UPDATE
, and DELETE
statements. Goravel makes this a breeze.
To see how read / write connections should be configured, let's look at this example:
Two keys have been added to the configuration array: read
and write
, 192.168.1.1
will be used as the host for the "read" connection, while 192.168.1.2
will be used for the "write" connection. The database prefix, character set, and all other options in the main mysql
array will be shared across both connections. When multiple values exist in the host
configuration array, a database host will be randomly chosen for each request.
Connection Pool
You can configure connection pool in the configuration file, reasonable configuration of connection pool parameters can greatly improve concurrency performance:
pool.max_idle_conns
Max idle connections
pool.max_open_conns
Max open connections
pool.conn_max_idletime
Connections max idle time
pool.conn_max_lifetime
Connections max lifetime
Model Definition
You can create a custom model based on the model file app/models/user.go
that comes with the framework. In the app/models/user.go
file, struct
has nested two frameworks, orm.Model
and orm.SoftDeletes
, they define id, created_at, updated_at
and deleted_at
respectively, orm.SoftDeletes
means that soft deletion is enabled for the model.
Model Convention
The model is named with a big hump;
Use the plural form of the model "snake naming" as the table name;
For example, the model name is UserOrder
, the table name is user_orders
.
Create Model
Specify Table Name
facades.Orm available functions
Connection
DB
Query
Transaction
WithContext
facades.Orm().Query & facades.Orm().Transaction available functions
Begin
Commit
Count
Create
Delete
Distinct
Driver
Exec
Find
FindOrFail
First
FirstOr
FirstOrCreate
FirstOrNew
FirstOrFail
ForceDelete
Get
Group
Having
Join
Limit
LockForUpdate
Model
Offset
Order
OrWhere
Paginate
Pluck
Raw
Rollback
Save
SaveQuietly
Scan
Scopes
Select
SharedLock
Table
Update
UpdateOrCreate
Where
WithoutEvents
WithTrashed
Query Builder
Inject Context
Specify Database Connection
If you define multiple database connections in the config/database.go
file, you can use them through the Connection
function of facades.Orm()
. The connection name passed to Connection
should be one of the connections configured in config/database.go
:
Generic Database Interface sql.DB
Generic database interface sql.DB, then use the functionality it provides:
Get Database Instance
Before each specific database operation, it's necessary to obtain an instance of the database.
Select
Query one line
Sometimes you may wish to perform some other action if no results are found. The findOr and firstOr methods will return a single model instance or, if no results are found, execute the given closure. You can set values to model in closure:
Query one or multiple lines by ID
Not found return error
When the primary key of the user table is string
type, you need to specify the primary key when calling Find
method
Query multiple lines
Retrieving Or Creating Models
The FirstOrCreate
method will attempt to locate a database record using the given column / value pairs. If the model can not be found in the database, a record will be inserted with the attributes resulting from merging the first argument with the optional second argument:
The FirstOrNew
method, like FirstOrCreate
, will attempt to locate a record in the database matching the given attributes. However, if a model is not found, a new model instance will be returned. Note that the model returned by FirstOrNew
has not yet been persisted to the database. You will need to manually call the Save
method to persist it:
Not Found Error
When not fount model, First
doesn't return error, if you want return an error, you can use FirstOrFail
:
Where
Limit
Offset
Order
Paginate
Query Single Column
Specify Table Query
If you want to query some aggregate data, you need to specify a specific table.
Specify a model
Specify a table
Count
Specify Fields
Select
allows you to specify which fields to retrieve from the database, by default the ORM retrieves all fields.
Group By & Having
Join
Create
Multiple create
created_at
andupdated_at
will be filled automatically.
Save Model
Update a existing model
Update a single column
When updating with
struct
, Orm will only update non-zero fields. You might want to usemap
to update attributes or useSelect
to specify fields to update. Note thatstruct
can only beModel
, if you want to update with nonModel
, you need to use.Table("users")
, however, theupdated_at
field cannot be updated automatically at this time.
Update or create
Query by name
, if not exist, create by name
, avatar
, if exists, update avatar
based on name
:
Delete
Delete by model, the number of rows affected by the statement is returned by the method:
Delete by ID
Multiple delete
Want to force delete a soft-delete data.
You can delete records with model associations via Select
:
Note: The associations will be deleted only if the primary key of the record is not empty, and Orm uses these primary keys as conditions to delete associated records:
If execute batch delete without any conditions, ORM doesn't do that and returns an error. So you have to add some conditions, or use native SQL.
Query Soft Delete Data
Filter Repetition
Get Driver
Execute Native SQL
Execute Native Update SQL
The number of rows affected by the statement is returned by the method:
Transaction
You can execute a transaction by Transaction
function.
You can also manually control the flow of the transaction yourself:
Scopes
Allows you to specify commonly used queries that can be referenced when methoed are called.
Raw Expressions
You can use the db.Raw
method to update fields:
Pessimistic Locking
The query builder also includes a few functions to help you achieve "pessimistic locking" when executing your select
statements.
To execute a statement with a "shared lock", you may call the SharedLock
method. A shared lock prevents the selected rows from being modified until your transaction is committed:
Alternatively, you may use the LockForUpdate
method. A "for update" lock prevents the selected records from being modified or from being selected with another shared lock:
Events
Orm models dispatch several events, allowing you to hook into the following moments in a model's lifecycle: Retrieved
, Creating
, Created
, Updating
, Updated
, Saving
, Saved
, Deleting
, Deleted
, ForceDeleting
, ForceDeleted
.
The Retrieved
event will dispatch when an existing model is retrieved from the database. When a new model is saved for the first time, the Creating
and Created
events will dispatch. The Updating
/ Updated
events will dispatch when an existing model is modified and the Save
method is called. The Saving
/ Saved
events will dispatch when a model is created or updated - even if the model's attributes have not been changed. Event names ending with -ing
are dispatched before any changes to the model are persisted, while events ending with -ed
are dispatched after the changes to the model are persisted.
To start listening to model events, define a DispatchesEvents
method on your model. This property maps various points of the model's lifecycle to your own event classes.
Note: Just register the events you need. Model events are not dispatched when doing batch operations through Orm.
Observers
Defining Observers
If you are listening for many events on a given model, you may use observers to group all of your listeners into a single class. Observer classes have method names which reflect the Eloquent events you wish to listen for. Each of these methods receives the affected model as their only argument. The make:observer
Artisan command is the easiest way to create a new observer class:
This command will place the new observer in your app/observers
directory. If this directory does not exist, Artisan will create it for you. Your fresh observer will look like the following:
To register an observer, you need to call the Observe
method on the model you wish to observe. You may register observers in the Boot
method of your application's app/providers/event_service_provider.go::Boot
service provider:
Note: If you set
DispatchesEvents
andObserver
at the same time, onlyDispatchesEvents
will be applied.
Parameter in Observer
The event
parameter will be passed to all observers:
Context
Get context that passed by facades.Orm().WithContext()
GetAttribute
Get the modified value, if not modified, get the original value, if there is no original value, return nil
GetOriginal
Get the original value, if there is no original value, return nil
IsDirty
Determine whether the field is modified
IsClean
IsDirty reverse
Query
Get a new Query, can be used with transaction
SetAttribute
Set a new value for field
Muting Events
You may occasionally need to temporarily "mute" all events fired by a model. You may achieve this using the WithoutEvents
method:
Saving A Single Model Without Events
Sometimes you may wish to "save" a given model without dispatching any events. You may accomplish this using the SaveQuietly
method:
Last updated