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='[email protected]'");
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 = "[email protected]";
$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='[email protected]'");
$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='[email protected]'")->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='[email protected]'");
$user = $query->execute();