-
Notifications
You must be signed in to change notification settings - Fork 2
Usingdatabase
jlesueur edited this page Apr 3, 2012
·
3 revisions
Before reading this tutorial you may want to familiarize yourself with these pages: MVC and AppInstanceLayout.
###Configuration
Add a section to config.yaml:
zinc:
db:
default:
driver: php_pgsql [also available are php_mysql, php_mssql, pdo(which is actually sqlite)]
database: mydb
username: mydbuser
host: localhost [this is the default]
port: 5432 [this is optional]
password: somepassword [this is optional]
second:
driver: php_pgsql [also available are php_mysql, php_mssql, pdo(which is actually sqlite)]
database: second
username: mydbuser
###Running Queries Sql* functions use the default connection, and are shortcuts to the DbConnection functions. They are the quickest way to get started. You can also get DbConnection objects using connection names.
$result = SqlQuery("select * from person where id = :id:int or username = :username", array('id' => 4, 'username' => 'rgigger'));
//to use a second connection:
$conn = DbModule::getConnection('second');
//there are quite a few different ways to run queries, which you can find at [[DbConnection]]
$result = $conn->FetchMap("select id, company_id, username from user", array('company_id', 'id'), array());
###Domain Objects Most objects in your database can be easily mapped on to objects. For example, a table named user with a foreign key(company_id) to a second table Company can be modeled with:
class User extends DbObject
{
function init()
{
$this->BelongsTo('Company');
}
}
class Company extends DbObject
{
function init()
{
$this->hasMany('User');
}
}
//get the user with id = 4;
$user = new User(4);
$user->username = 'rgigger';
$user->company_id = 1;
$user->save();
$company = $user->Company;
$users = User::find(array('company_id' => 1));
$users = $company->User;
Find more info at DbObject