How to use Phalcon's query builder?

by tressie.damore , in category: PHP Frameworks , 2 years ago

How to use Phalcon's query builder?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by edmond_brakus , a year ago

@tressie.damore 

Phalcon's query builder allows you to create and execute SQL queries without writing raw SQL code. Here's a brief guide on how to use it:

  1. Create a new instance of the query builder using the PhalconMvcModelQueryBuilder class:
1
$queryBuilder = new PhalconMvcModelQueryBuilder();


  1. Set the query type using the from() method. This specifies the table name and sets the query type to "SELECT".
1
$queryBuilder->from('users');


  1. Use the columns() method to select specific columns:
1
$queryBuilder->columns(['id', 'username']);


  1. Add conditions using the where() method:
1
$queryBuilder->where('username = :username:', ['username' => 'john_doe']);


  1. Use the orderBy() method to sort the results:
1
$queryBuilder->orderBy('id ASC');


  1. To execute the query, use the getQuery() and execute() methods:
1
2
$query = $queryBuilder->getQuery();
$result = $query->execute();


That's it! You can find further documentation and examples in the official Phalcon documentation.