Getting data from a database
Most applications use databases today. Be it a small website or a social network, at least some parts are powered by databases.
Yii introduces three ways to allow you to work with databases. They are as follows:
Active Record
Query Builder
SQL via DAO
We will use all these methods to get data from the film
, film_actor
, and actor
tables and show it in a list. Also, we will compare the execution time and memory usage to determine in which cases we should use these methods.
Getting ready
Create a new application using the Composer package manager, as described in the official guide at http://www.yiiframework.com/doc-2.0/guide-start-installation.html.
Download the Sakila database from http://dev.mysql.com/doc/index-other.html.
Execute the downloaded SQLs; first schema, then data.
Configure the DB connection in
config/main.php
to use the Sakila database.Use Gii to create models for the actor and film tables.
How to do it…
Create
app/controllers/DbController.php
as follows:<...