phalcon Database Management Database management using Phalcon Model


Example

A model for a new table can be created by running the following commend from the terminal root location:

phalcon model <table-name>

Let us take the Model Users.

SELECT

There are two default functions to do select operation in phalcon, find() and findFirst()

findFirst() is used to get the first row which satisfies the conditions that we are passing. It returns a single object with the data in first row.

Example:

$user = Users::findFirst("active=1 AND verified=1 AND email='a@a.com'");

This returns the user with the given email and the value of the column verified and active is 1

find() is used to get all rows which satisfies the conditions we are passing.

Example:

$users = Users::find("active=1 AND verified=1");

This returns the users with the value of the column verified and active is 1

INSERT

Insert can be done using the following code:

$user = new Users();

$user->name = "Arun";
$user->email = "abc@gmail.com";
$user->verified = 1;
$user->active = 1;

$user->save();

A new row with the these values will be inserted.

UPDATE

Update can be done using the following code:

First we have to select the row we have to update using findFirst()

$user = Users::findFirst("email='a@a.com'");

$user->verified = 0;
$user->active = 0;

$user->save();

This will change the values for the column verified and active for the row with given email.

DELETE Delete can also be done using the findFirst()

Example:

Users::findFirst("email='a@a.com'")->delete();

This will delete the row with given email.

You can also execute custom sql commands with models using the following code:

$query = $this->modelsManager->createQuery("SELECT * FROM Users WHERE email='a@a.com'");

$user = $query->execute();